year
stringclasses
1 value
day
stringclasses
25 values
part
stringclasses
2 values
question
stringclasses
50 values
answer
stringclasses
49 values
solution
stringlengths
143
12.8k
language
stringclasses
3 values
2024
11
1
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?
193607
stones = open('input.txt').read().strip().split(' ') stones = [int(x) for x in stones] def get_next_stones(): for i in range(len(stones)): if stones[i] == 0: stones[i] = 1 elif len(str(stones[i])) % 2 == 0: num = str(stones[i]) # print(num) stones[i] = int(num[:len(num)//2]) stones.append(int(num[len(num)//2:])) else: stones[i] *= 2024 for i in range(25): # print(stones) get_next_stones() print(len(stones))
python
2024
11
1
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?
193607
def rules(n): if n == 0: return [1] s = str(n) if len(s) % 2 == 0: l = len(s) // 2 return [int(s[:l]), int(s[l:])] return [n * 2024] def calc(stone, blinks): if blinks == 0: return 1 new = rules(stone) return sum(calc(num, blinks - 1) for num in new) res = 0 stones = list(map(int, open('i.txt').read().split())) for stone in stones: res += calc(stone, 25) print(res)
python
2024
11
1
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?
193607
def blink(stones): newStones = [] for stone in stones: if stone == 0: newStones.append(1) continue n = len(str(stone)) if n % 2 == 0: newStones.append(int(str(stone)[:(n//2)])) newStones.append(int(str(stone)[(n//2):])) continue newStones.append(stone * 2024) return newStones def get_num_stones(stones): for _ in range(25): stones = blink(stones) return len(stones) if __name__ == "__main__": # Open file 'day11-1.txt' in read mode with open('day11-1.txt', 'r') as f: stones = [] for line in f: stones = [int(val) for val in line.strip().split()] print("Number of Stones: " + str(get_num_stones(stones)))
python
2024
11
1
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?
193607
def get_next_array(stones): res = [] for stone in stones: if stone == 0: res.append(1) elif len(str(stone)) % 2 == 0: stone_str = str(stone) res.append(int(stone_str[0:len(stone_str)//2])) res.append(int(stone_str[len(stone_str)//2:])) else: res.append(stone * 2024) return res with open('input.txt') as f: stones = [int(s) for s in f.read().split()] for i in range(25): stones = get_next_array(stones) print(len(stones))
python
2024
11
1
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?
193607
from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open("input.txt") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 25) for stone in stones]) print(result)
python
2024
11
2
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?
229557103025807
from functools import cache with open("input.txt") as input_file: input_text = input_file.read().splitlines() @cache def stones_created(num, rounds): if rounds == 0: return 1 elif num == 0: return stones_created(1, rounds - 1) elif len(str(num)) % 2 == 0: return stones_created( int(str(num)[: len(str(num)) // 2]), rounds - 1 ) + stones_created(int(str(num)[len(str(num)) // 2 :]), rounds - 1) else: return stones_created(num * 2024, rounds - 1) nums = [int(x) for x in input_text[0].split()] print(sum(stones_created(x, 75) for x in nums))
python
2024
11
2
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?
229557103025807
from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open("input.txt") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 75) for stone in stones]) print(result)
python
2024
11
2
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?
229557103025807
from functools import lru_cache def is_even(num): count = 0 a = num while a: a //= 10 count += 1 return count % 2 == 0 @lru_cache(maxsize=1000_000) def check_stone(stone): if stone == 0: return (1, -1) if is_even(stone): s = str(stone) l = s[: len(s) // 2] r = s[len(s) // 2 :] return (int(l), int(r)) return (stone * 2024, -1) in_date = "" with open("input.txt") as f: in_date = f.read() init_stones = [int(i) for i in in_date.strip().split()] total_nums = {} for i in init_stones: res = total_nums.get(i, 0) + 1 total_nums[i] = res for iter in range(75): new_total_nums = {} for n, c in total_nums.items(): l, r = check_stone(n) if r != -1: r_count = new_total_nums.get(r, 0) new_total_nums[r] = r_count + (1 * c) l_count = new_total_nums.get(l, 0) new_total_nums[l] = l_count + (1 * c) total_nums = new_total_nums total = sum(total_nums.values()) print(total)
python
2024
11
2
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?
229557103025807
from collections import defaultdict import sys sys.setrecursionlimit(2**30) with open("./day_11.in") as fin: raw_nums = list(map(int, fin.read().strip().split())) nums = defaultdict(int) for x in raw_nums: nums[x] += 1 def blink(nums: dict): new_nums = defaultdict(int) for x in nums: l = len(str(x)) if x == 0: new_nums[1] += nums[0] elif l % 2 == 0: new_nums[int(str(x)[:l//2])] += nums[x] new_nums[int(str(x)[l//2:])] += nums[x] else: new_nums[x * 2024] += nums[x] return new_nums for i in range(75): nums = blink(nums) ans = 0 for x in nums: ans += nums[x] print(ans)
python
2024
11
2
--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?
229557103025807
try: with open("11/input.txt", "r") as file: data = file.read() except Exception: with open("input.txt", "r") as file: data = file.read() data = data.split(" ") class Stone: def __init__(self, n, ntimes = 1): self.n = int(n) self.ntimes = ntimes def evolve(self): if self.n == 0: self.n = 1 return [self] elif len(str(self.n)) % 2 == 0: return [Stone(str(self.n)[:len(str(self.n))//2], self.ntimes), Stone(str(self.n)[len(str(self.n))//2:], self.ntimes)] else: self.n = self.n*2024 return [self] def __str__(self): return "{"+str(self.n)+","+str(self.ntimes)+"}" stones = [] for i in data: stones.append(Stone(i)) blinks = 75 for blink in range(blinks): newstones = [] print("Blink ", blink) #print(" ".join([x.__str__() for x in stones])) print(len(stones)) for i in range(len(stones)): for stone in stones[i].evolve(): newstones.append(stone) stones = newstones if True: i = -1 while i < len(stones)-1: i = i+1 j = i while j < len(stones)-1: j = j+1 if stones[i].n == stones[j].n: stones[i].ntimes += stones[j].ntimes del stones[j] j = j-1 print("\n\n", len(stones)) res = 0 for i in stones: res += i.ntimes print(res)
python
2024
12
1
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?
1377008
def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] perim = 0 for ray_x in range(min_x , max_x + 1): is_in = False side_count = 0 for ray_y in range(min_y, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count for ray_y in range(min_y , max_y + 1): is_in = False side_count = 0 for ray_x in range(min_x, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count return perim def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open("12_input.txt", "r") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()
python
2024
12
1
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?
1377008
from collections import deque inp = [] with open('day12-data.txt', 'r') as f: for line in f: inp.append(list(line.strip())) # print(inp) num_rows = len(inp) num_cols = len(inp[0]) def in_bounds(rc): r, c = rc return (0 <= r < num_rows) and (0 <= c < num_cols) def get_plant(rc): r, c = rc return inp[r][c] def get_neighbors(rc): r, c = rc neighbors = [] ds = [(-1, 0), (0, 1), (1, 0), (0, -1)] # NESW for (dr, dc) in ds: neighbors.append((r + dr, c + dc)) return [n for n in neighbors if in_bounds(n)] def get_plant_neighbors(rc): neighbors = get_neighbors(rc) return [n for n in neighbors if get_plant(n)==get_plant(rc)] # BFS def get_region(rc): visited = set() region = set() queue = deque([rc]) while queue: node = queue.popleft() if node not in visited: visited.add(node) # visit node region.add(node) # add all unvisited neighbors to the queue neighbors = get_plant_neighbors(node) unvisited_neighbors = [n for n in neighbors if n not in visited] # print(f'At node {node}, ns: {neighbors}, unvisited: {unvisited_neighbors}') queue.extend(unvisited_neighbors) return region def calc_perimeter(region): perimeter = 0 for rc in region: plant = get_plant(rc) neighbors = get_plant_neighbors(rc) # Boundary adds to perimeter perimeter += 4 - len(neighbors) return perimeter regions = [] visited = set() for r in range(num_rows): for c in range(num_cols): rc = (r, c) if rc not in visited: region = get_region(rc) visited |= region regions.append(region) # print(regions) total_price = 0 for region in regions: plant = get_plant(next(iter(region))) area = len(region) perimeter = calc_perimeter(region) price = area * perimeter total_price += price # print(f'{plant} (area: {area}, perimeter: {perimeter}): {region}') print(total_price)
python
2024
12
1
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?
1377008
input = open("day_12\input.txt", "r").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f"{'!'}{row}{'!'}" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, perimeter if not input[i][j] == char: perimeter += 1 return visited.add((i,j)) global_visited.add((i, j)) area += 1 for (dy, dx) in directions: if not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if not input[i][j] == "!" and not (i, j) in global_visited: visited = set() area = 0 perimeter = 0 explore(input[i][j], i, j) total += area * perimeter print(f"The total price of fencing all the regions is {total}")
python
2024
12
1
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?
1377008
from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * perimeter total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)
python
2024
12
1
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?
1377008
from typing import List from pprint import pprint as pprint INPUT_FILE = "input.txt" visited = set() class Plot: def __init__(self, plant: str, area: int, perimeter: int): self.plant = plant self.area = area self.perimeter = perimeter def __repr__(self): return f"Plot({self.plant}, {self.area}, {self.perimeter})" def __str__(self): return f"Plot({self.plant}, {self.area}, {self.perimeter})" def readInput() -> List[List[str]]: with open(INPUT_FILE, 'r') as f: return [list(line.strip()) for line in f.readlines()] def findPlot(grid: List[List[str]], currentPlot: Plot, currentLocation: tuple[int, int]) -> Plot: plot = Plot(currentPlot.plant, currentPlot.area, currentPlot.perimeter) visited.add(currentLocation) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] for direction in directions: x = currentLocation[0] + direction[0] y = currentLocation[1] + direction[1] if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]): plot.perimeter += 1 continue if grid[x][y] != plot.plant: plot.perimeter += 1 continue if (x, y) in visited: continue plot.area += 1 plot = findPlot(grid, plot, (x, y)) return plot def getPlots(grid: List[List[str]]) -> List[Plot]: plots = [] for i in range(len(grid)): for j in range(len(grid[0])): if (i, j) in visited: continue plot = findPlot(grid, Plot(grid[i][j], 1, 0), (i, j)) plots.append(plot) return plots def calculateCosts(plots: List[Plot]) -> int: cost = 0 for plot in plots: cost += plot.area * plot.perimeter return cost def main(): grid = readInput() pprint(grid) plots = getPlots(grid) pprint(plots) print(f'Cost: {calculateCosts(plots)}') if __name__ == "__main__": main()
python
2024
12
2
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?
815788
input = open("day_12\input.txt", "r").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f"{'!'}{row}{'!'}" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, sides visited.add((i,j)) global_visited.add((i,j)) area += 1 for (dy,dx) in directions: if input[i + dy][j + dx] != char: sides += [((dy,dx), (i,j))] elif not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) def calculate_sides(sides): unique_sides = 0 while len(sides) > 0: current_side = sides[0] sides = explore_side(current_side, sides[0:]) unique_sides += 1 if current_side in sides: sides.remove(current_side) return unique_sides def explore_side(side, sides): if side[0] == (1, 0) or side[0] == (-1, 0): targets = [(side[0], (side[1][0], side[1][1] - 1)), (side[0], (side[1][0], side[1][1] + 1))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) elif side[0] == (0, 1) or side[0] == (0, -1): targets = [(side[0], (side[1][0] + 1, side[1][1])), (side[0], (side[1][0] - 1, side[1][1]))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) return sides input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if input[i][j] != "!" and not (i, j) in global_visited: visited = set() area = 0 sides = [] explore(input[i][j], i, j) total += area * calculate_sides(sides) print(f"The total price of fencing all the regions is {total}")
python
2024
12
2
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?
815788
def add_to_region_from(grid, loc, region, visited): region.add(loc) visited.add(loc) neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] neighbors = [pt for pt in neighbors if pt[0] in range(len(grid)) and pt[1] in range(len(grid))] for neighbor in neighbors: if grid[loc[0]][loc[1]] == grid[neighbor[0]][neighbor[1]] and not neighbor in visited: add_to_region_from(grid, neighbor, region, visited) def get_area(region): return len(region) def get_sides(region): sides = 0 visited_edges = set() sorted_region = sorted(list(region)) for loc in sorted_region: above = (loc[0] - 1, loc[1]) if above not in region: visited_edges.add((above, 'bottom')) if ((above[0], above[1] - 1), 'bottom') not in visited_edges and ((above[0], above[1] + 1), 'bottom') not in visited_edges: sides += 1 below = (loc[0] + 1, loc[1]) if below not in region: visited_edges.add((below, 'top')) if ((below[0], below[1] - 1), 'top') not in visited_edges and ((below[0], below[1] + 1), 'top') not in visited_edges: sides += 1 left = (loc[0], loc[1] - 1) if left not in region: visited_edges.add((left, 'right')) if ((left[0] - 1, left[1]), 'right') not in visited_edges and ((left[0] + 1, left[1]), 'right') not in visited_edges: sides += 1 right = (loc[0], loc[1] + 1) if right not in region: visited_edges.add((right, 'left')) if ((right[0] - 1, right[1]), 'left') not in visited_edges and ((right[0] + 1, right[1]), 'left') not in visited_edges: sides += 1 return sides def get_corners(region): corners = 0 for loc in region: outer_top_left = [((0, -1), False), ((-1, 0), False)] outer_top_right = [((0, 1), False), ((-1, 0), False)] outer_bottom_right = [((0, 1), False), ((1, 0), False)] outer_bottom_left = [((0, -1), False), ((1, 0), False)] inner_top_left = [((0, 1), True), ((1, 0), True), ((1, 1), False)] inner_top_right = [((0, -1), True), ((1, 0), True), ((1, -1), False)] inner_bottom_right = [((0, -1), True), ((-1, 0), True), ((-1, -1), False)] inner_bottom_left = [((0, 1), True), ((-1, 0), True), ((-1, 1), False)] all_neighbors = [outer_top_left, outer_top_right, outer_bottom_right, outer_bottom_left, inner_top_left, inner_top_right, inner_bottom_right, inner_bottom_left] corners += sum([all([((loc[0] + pt[0][0], loc[1] + pt[0][1]) in region) == pt[1] for pt in neighbor]) for neighbor in all_neighbors]) return corners def get_perimeter(region): perimeter = 0 for loc in region: neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] perimeter += len([pt for pt in neighbors if pt not in region]) return perimeter with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] visited = set() regions = [] for i in range(len(grid)): for j in range(len(grid[i])): if not (i, j) in visited: region = set() add_to_region_from(grid, (i, j), region, visited) regions.append(region) visited.add((i, j)) total_price = 0 for region in regions: price = get_area(region) * get_corners(region) total_price += price print(total_price)
python
2024
12
2
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?
815788
from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def count_corners(plant, x, y): up = data[y - 1][x] if y - 1 >= 0 else None down = data[y + 1][x] if y + 1 < ymax else None left = data[y][x - 1] if x - 1 >= 0 else None right = data[y][x + 1] if x + 1 < xmax else None count = sum(1 for i in (up, down, left, right) if i == plant) corners = 0 if count == 0: return 4 if count == 1: return 2 if count == 2: if left == right == plant or up == down == plant: return 0 corners += 1 if up == left == plant and (y - 1 >= 0 and x - 1 >= 0) and data[y - 1][x - 1] != plant: corners += 1 if up == right == plant and (y - 1 >= 0 and x + 1 < xmax) and data[y - 1][x + 1] != plant: corners += 1 if down == left == plant and (y + 1 < ymax and x - 1 >= 0) and data[y + 1][x - 1] != plant: corners += 1 if down == right == plant and (y + 1 < ymax and x + 1 < xmax) and data[y + 1][x + 1] != plant: corners += 1 return corners def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 corners = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 corners += count_corners(plant, xi, yi) q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * corners total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)
python
2024
12
2
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?
815788
def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] # vertical rays hits = {} for ray_x in range(min_x - 1, max_x + 1): is_in = False hits[ray_x] = [] for ray_y in range(min_y - 1, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_x].append((ray_y, is_in)) side_count = 0 for i, hit_x in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_x]: if (y, is_in) not in hits[hit_x - 1]: side_count += 1 # horizontal rays hits = {} for ray_y in range(min_y - 1, max_y + 1): is_in = False hits[ray_y] = [] for ray_x in range(min_x - 1, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_y].append((ray_x, is_in)) for i, hit_y in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_y]: if (y, is_in) not in hits[hit_y - 1]: side_count += 1 return side_count def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open("12_input.txt", "r") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()
python
2024
12
2
--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?
815788
from collections import deque def get_total_cost(farm): n = len(farm) m = len(farm[0]) def in_bounds(r, c): return (0 <= r < n) and (0 <= c < m) def get_val(r, c): return farm[r][c] def get_neighbours(r, c): neighbours = [] dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)] for (dr, dc) in dirs: neighbours.append((r + dr, c + dc)) return [neighbour for neighbour in neighbours if in_bounds(neighbour[0], neighbour[1])] def get_val_neighbours(r, c): neighbours = get_neighbours(r, c) return [neighbour for neighbour in neighbours if get_val(neighbour[0], neighbour[1]) == get_val(r, c)] def get_region(r, c): visited = set() region = set() queue = deque([(r, c)]) while queue: node = queue.popleft() if node not in visited: visited.add(node) region.add(node) neighbours = get_val_neighbours(node[0], node[1]) neighbours = [neighbour for neighbour in neighbours if neighbour not in visited] queue.extend(neighbours) return region def calc_edges(region): edges = 0 for (r, c) in region: if ((r - 1, c) not in region): if not (((r, c - 1) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r + 1, c) not in region): if not (((r, c - 1) in region) and ((r + 1, c - 1) not in region)): edges += 1 if ((r, c - 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r, c + 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c + 1) not in region)): edges += 1 return edges regions = [] visited = set() for i in range(n): for j in range(m): if (i, j) not in visited: region = get_region(i, j) visited |= region regions.append(region) cost = 0 for region in regions: nextRegion = next(iter(region)) val = get_val(nextRegion[0], nextRegion[1]) area = len(region) edges = calc_edges(region) price = area * edges cost += price return cost if __name__ == "__main__": # Open file 'day12-2.txt' in read mode with open('day12-2.txt', 'r') as f: farm = [] for line in f: farm.append(line.strip()) print("Total fencing cost: " + str(get_total_cost(farm)))
python
2024
13
1
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
34787
with open("input.txt") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix("Button A: ").split(", ") ) button_a_move = ( int(button_a_move_x.removeprefix("X+")), int(button_a_move_y.removeprefix("Y+")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix("Button B: ").split(", ") ) button_b_move = ( int(button_b_move_x.removeprefix("X+")), int(button_b_move_y.removeprefix("Y+")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix("Prize: ").split(", ") target = (int(target_x.removeprefix("X=")), int(target_y.removeprefix("Y="))) min_cost = float("inf") for a_presses in range(101): for b_presses in range(101): if ( a_presses * button_a_move[0] + b_presses * button_b_move[0], a_presses * button_a_move[1] + b_presses * button_b_move[1], ) == target: min_cost = min(min_cost, a_presses * 3 + b_presses) if min_cost < float("inf"): total += min_cost print(total)
python
2024
13
1
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
34787
import re with open("./day_13.in") as fin: lines = fin.read().strip().split("\n\n") def parse(x): lines = x.split("\n") a = list(map(int, re.findall(r"Button A: X\+(\d+), Y\+(\d+)", lines[0])[0])) b = list(map(int, re.findall(r"Button B: X\+(\d+), Y\+(\d+)", lines[1])[0])) p = list(map(int, re.findall(r"Prize: X=(\d+), Y=(\d+)", lines[2])[0])) return a, b, p prices = [] for a, b, p in [parse(line) for line in lines]: def test(i, j): x = a[0] * i + b[0] * j y = a[1] * i + b[1] * j return (x, y) == tuple(p) va = 1<<30 for i in range(100): for j in range(100): if test(i, j): va = min(va, 3*i + j) if va < 1<<30: prices.append(va) spent = 0 print(sum(prices))
python
2024
13
1
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
34787
from typing import List from pprint import pprint as pprint from functools import cache INPUT_FILE = "input.txt" MAX_PRIZE = 401 class Button: def __init__(self, price: int, d_x: int, d_y: int): self.price = price self.d_x = d_x self.d_y = d_y def __repr__(self): return f"Button({self.price}, {self.d_x}, {self.d_y})" def __str__(self): return f"Button({self.price}, {self.d_x}, {self.d_y})" class Prize: def __init__(self, x: int, y: int): self.x = x self.y = y def __repr__(self): return f"Price({self.x}, {self.y})" def __str__(self): return f"Price({self.x}, {self.y})" def readInput() -> List[str]: with open(INPUT_FILE, 'r') as f: return f.read().split('\n\n') def parseInput(data: str) -> tuple[Prize, tuple[Button, Button]]: a, b, prize = data.splitlines() button_a = Button(3, int(a.split("X+")[1].split(",")[0]), int(a.split("Y+")[1])) button_b = Button(1, int(b.split("X+")[1].split(",")[0]), int(b.split("Y+")[1])) prize = Prize(int(prize.split("X=")[1].split(",")[0]), int(prize.split("Y=")[1])) return (prize, (button_a, button_b)) @cache def getCost(prize: Prize, buttons: tuple[Button, Button]) -> int: # lowest_cost = MAX_PRIZE for a in range(100): for b in range(100): if prize.x == buttons[0].d_x*a+buttons[1].d_x*b and prize.y == buttons[0].d_y*a+buttons[1].d_y*b: return a * buttons[0].price + b * buttons[1].price return 0 def costs(machines: List[tuple[Prize, tuple[Button, Button]]]) -> List[int]: costs = [] for machine in machines: costs.append(getCost(machine[0], machine[1])) return costs def main(): data = readInput() # pprint(data) machines = [parseInput(line) for line in data] # pprint(machines) costs_list = costs(machines) # pprint(costs_list) print(f"Result: {sum(costs_list)}") if __name__ == "__main__": main()
python
2024
13
1
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
34787
f = open("input.txt") machines = [elem.split("\n") for elem in f.read().split("\n\n")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and a <= 100 and int(b) == b and b <= 100): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split(":")[1].split(",")]) B_button = tuple([int(text[3:]) for text in machine[1].split(":")[1].split(",")]) prize = tuple([int(text[3:]) for text in machine[2].split(":")[1].split(",")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)
python
2024
13
1
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
34787
import os def reader(): return open(f"input.txt", 'r').read().splitlines() def part1(): f = list(map(lambda s: s.split('\n'), '\n'.join(reader()).split('\n\n'))) M = [] for l in f: Ax = int(l[0][(l[0].find('X+') + 2):l[0].find(',')]) Ay = int(l[0][(l[0].find('Y+') + 2):]) Bx = int(l[1][(l[1].find('X+') + 2):l[1].find(',')]) By = int(l[1][(l[1].find('Y+') + 2):]) X = int(l[2][(l[2].find('X=') + 2):l[2].find(',')]) Y = int(l[2][(l[2].find('Y=') + 2):]) M.append([(Ax, Ay), (Bx, By), (X, Y)]) t = 0 for m in M: l = -1, 0 for i in range(101): for j in range(101): cost = 3 * i + j pos = i * m[0][0] + j * m[1][0], i * m[0][1] + j * m[1][1] if pos == m[2]: l = (0, cost) if l[0] == -1 else (0, min(l[1], cost)) if l[0] == 0: t += l[1] print(t) part1()
python
2024
13
2
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
85644161121698
def get_cheapest(machine): A = machine[0] B = machine[1] prize = (machine[2][0] + 10000000000000, machine[2][1] + 10000000000000) af = (A[1] / A[0]) bf = (B[1] / B[0]) xIntersection = round((prize[0] * af - prize[1]) / (af - bf)) if xIntersection % B[0] != 0: return 0 b = xIntersection // B[0] rem = ((prize[0] - B[0] * b), (prize[1] - B[1] * b)) if rem[0] % A[0] != 0: return 0 a = rem[0] // A[0] if ((B[0] * b) + (A[0] * a) == prize[0] and (B[1] * b) + (A[1] * a)) == prize[1]: return b + (a * 3) return 0 def get_fewest_tokens(machines): tokens = 0 for machine in machines: tokens += get_cheapest(machine) return tokens if __name__ == "__main__": # Open file 'day13-2.txt' in read mode with open('day13-2.txt', 'r') as f: machines = [] A = (0, 0) B = (0, 0) prize = (0, 0) for i, line in enumerate(f): line = line.strip() if i % 4 == 0: A = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 1: B = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 2: prize = (int(line[line.find('=') + 1: line.find(',')]), int(line[line.find(',') + 4:])) machines.append([ A, B, prize ]) else: A = (0, 0) B = (0, 0) prize = (0, 0) print("Fewest number of tokens: " + str(get_fewest_tokens(machines)))
python
2024
13
2
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
85644161121698
f = open("input.txt") machines = [elem.split("\n") for elem in f.read().split("\n\n")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize X_prize += 10000000000000 Y_prize += 10000000000000 b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and int(b) == b): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split(":")[1].split(",")]) B_button = tuple([int(text[3:]) for text in machine[1].split(":")[1].split(",")]) prize = tuple([int(text[3:]) for text in machine[2].split(":")[1].split(",")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)
python
2024
13
2
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
85644161121698
import re from typing import Tuple, List def parse_input(file_path: str) -> List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: """ Parses the input file to extract button and prize coordinates. The input file should contain lines formatted as: "Button A: X+<int>, Y+<int> Button B: X+<int>, Y+<int> Prize: X=<int>, Y=<int>" Args: file_path (str): The path to the input file. Returns: List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: A list of tuples, each containing: - A tuple representing the coordinates of Button A (X, Y). - A tuple representing the coordinates of Button B (X, Y). - A tuple representing the coordinates of the Prize (X, Y) with 10000000000000 added to each coordinate. """ pattern = re.compile(r"Button A: X\+(\d+), Y\+(\d+)\s+Button B: X\+(\d+), Y\+(\d+)\s+Prize: X=(\d+), Y=(\d+)") results = [] with open(file_path, 'r') as file: content = file.read() matches = pattern.findall(content) for match in matches: button_a = (int(match[0]), int(match[1])) button_b = (int(match[2]), int(match[3])) prize = (int(match[4]) + 10000000000000, int(match[5]) + 10000000000000) results.append((button_a, button_b, prize)) return results def solve(scenario: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]) -> int: """ Solves the given scenario by finding integers a and b such that the linear combination of the vectors (ax, ay) and (bx, by) equals the target vector (tx, ty). Args: scenario (Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]): A tuple containing three tuples, each representing a vector in the form (x, y). The first two tuples are the vectors (ax, ay) and (bx, by), and the third tuple is the target vector (tx, ty). Returns: int: The result of the expression 3 * a + b if the linear combination is valid, otherwise 0. """ (ax, ay), (bx, by), (tx, ty) = scenario b = (tx * ay - ty * ax) // (ay * bx - by * ax) a = (tx * by - ty * bx) // (by * ax - bx * ay) if ax * a + bx * b == tx and ay * a + by * b == ty: return 3 * a + b else: return 0 if __name__ == "__main__": file_path = 'input.txt' parsed_data = parse_input(file_path) results = [solve(scenario) for scenario in parsed_data] print(sum(results))
python
2024
13
2
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
85644161121698
import re def min_cost_for_prize(prize, a, b): prize_x = prize[0] prize_y = prize[1] a_x = a[0] a_y = a[1] b_x = b[0] b_y = b[1] if (prize_x * b_y - b_x * prize_y) % (a_x * b_y - b_x * a_y) != 0: return (False, -1) a_val = (prize_x * b_y - b_x * prize_y) // (a_x * b_y - b_x * a_y) if (prize_x - a_x * a_val) % b_x != 0: return (False, -1) b_val = (prize_x - a_x * a_val) // b_x return (True, 3 * a_val + b_val) with open('input.txt') as f: claw_strs = f.read().split("\n\n") claw_data = [] for claw_input in claw_strs: lines = claw_input.splitlines() claw = dict() claw['A'] = tuple(map(int, re.match("Button A: X\\+(\\d+), Y\\+(\\d+)", lines[0]).groups())) claw['B'] = tuple(map(int, re.match("Button B: X\\+(\\d+), Y\\+(\\d+)", lines[1]).groups())) claw['Prize'] = tuple(map(lambda n: n + 10000000000000, map(int, re.match("Prize: X=(\\d+), Y=(\\d+)", lines[2]).groups()))) claw_data.append(claw) total_cost = 0 for claw in claw_data: res = min_cost_for_prize(claw['Prize'], claw['A'], claw['B']) if res[0]: total_cost += res[1] print(total_cost)
python
2024
13
2
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
85644161121698
with open("input.txt") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix("Button A: ").split(", ") ) button_a_move = ( int(button_a_move_x.removeprefix("X+")), int(button_a_move_y.removeprefix("Y+")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix("Button B: ").split(", ") ) button_b_move = ( int(button_b_move_x.removeprefix("X+")), int(button_b_move_y.removeprefix("Y+")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix("Prize: ").split(", ") target = ( int(target_x.removeprefix("X=")) + 10000000000000, int(target_y.removeprefix("Y=")) + 10000000000000, ) sol_a, sol_b = ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), ) if ( ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and ( (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and sol_a > 0 and sol_b > 0 ): total += 3 * sol_a + sol_b print(total)
python
2024
14
1
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
219150360
import re def read_input(): robots = [] with open("./input.txt") as f: while True: line = f.readline() if not line: break numbers = re.findall(r"-?\d+", line) robots.append([int(s) for s in numbers]) return robots def move_robot_n_step(robot, width, height, n): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] for i in range(n): x0 = (x0 + vx) % width y0 = (y0 + vy) % height return x0, y0 def move_robot_one_step(robot, width, height): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] robot[0] = (x0 + vx) % width robot[1] = (y0 + vy) % height def get_quadrant(x, y, width, height): cx = width // 2 cy = height // 2 if x < cx and y < cy: return 4 elif x < cx and y > cy: return 3 elif x > cx and y < cy: return 1 elif x > cx and y > cy: return 2 else: return -1 def solve_part1(robots, width, height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 100) iq = get_quadrant(x, y, width, height) q[iq] += 1 print(f"q1: {q[1]}, q2: {q[2]}, q3: {q[3]}, q4: {q[4]}") return q[1] * q[2] * q[3] * q[4] def solve_part2(robots, width, height): best_iter = None min_safe = float('inf') for i in range(width * height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 1) robot[0] = x robot[1] = y iq = get_quadrant(x, y, width, height) q[iq] += 1 safe = q[1] * q[2] * q[3] * q[4] if safe < min_safe: min_safe = safe best_iter = i if i == 99: print("At 100 sec, ", safe) print(f"best iter {best_iter}, min safe {min_safe}") if __name__ == "__main__": robots = read_input() width = 101 height = 103 multiply = solve_part1(robots, width, height) print(f"Part 1: the product is {multiply}") solve_part2(robots, width, height)
python
2024
14
1
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
219150360
from collections import Counter import re width = 101 #11 half_width = width // 2 height = 103 #7 half_height = height // 2 class Robot: def __init__(self, px, py, vx, vy) -> None: self.px = px self.py = py self.vx = vx self.vy = vy self.q = None def move(self, seconds): self.px = (self.px + self.vx * seconds) % width self.py = (self.py + self.vy * seconds) % height self.q = self.quadrant() def quadrant(self): quadrants = { (True, True): 1, (True, False): 3, (False, True): 2, (False, False): 4, } return quadrants[(self.px < half_width, self.py < half_height)] if self.px != half_width and self.py != half_height else None with open('input.txt') as f: robots = [Robot(*map(int, re.findall(r'(-?\d+)', line))) for line in f] def print_grid(robots: list[Robot]): grid = [list('.' * width) for _ in range(height)] for robot in robots: val = grid[robot.py][robot.px] grid[robot.py][robot.px] = '1' if val == '.' else str(int(val) + 1) print('\n'.join(''.join(row) for row in grid)) quadrants = [] for robot in robots: robot.move(100) quadrants.append(robot.q) counter = Counter(quadrants) counter.pop(None) print(counter[1] * counter[2] * counter[3] * counter[4])
python
2024
14
1
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
219150360
#!/usr/bin/python3 class Robot: def __init__(self, position, velocity): self.position = position self.velocity = velocity def teleport(self, pos:int, dim:int): """Move to opposite side rather than out of the space.""" return pos - dim if pos >= dim else dim - abs(pos) if pos < 0 else pos def move_robot(self, width:int, height:int): """Move robot according to its velocity.""" self.position = [self.position[0] + self.velocity[0], self.position[1] + self.velocity[1]] if self.position[0] not in range(width): self.position[0] = self.teleport(self.position[0], width) if self.position[1] not in range(height): self.position[1] = self.teleport(self.position[1], height) # Get initial position and velocity for each robot. with open("input.txt") as file: robots = {} for l, line in enumerate(file): robot_name = "robot_" + str(l+1) pos = line.split()[0].strip("p=").split(",") vel = line.split()[1].strip("v=").split(",") robots[robot_name] = Robot([int(pos[0]),int(pos[1])], [int(vel[0]),int(vel[1])]) # Move robots for 100 seconds in a space 101 tiles wide and 103 tiles tall. for robot in robots: for sec in range(100): robots[robot].move_robot(101, 103) # Determine the safety factor. quadrant_1 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] < 51] quadrant_2 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] < 51] quadrant_3 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] > 51] quadrant_4 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] > 51] print("Safety factor after 100 seconds:", len(quadrant_1) * len(quadrant_2) * len(quadrant_3) * len(quadrant_4))
python
2024
14
1
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
219150360
from typing import List EXAMPLE: bool = False WIDTH: int = 11 if EXAMPLE else 101 HEIGHT: int = 7 if EXAMPLE else 103 INPUT_FILE: str = "e_input.txt" if EXAMPLE else "input.txt" class Robot: def __init__(self, x: int, y: int, v_x: int, v_y: int): self.x = x self.y = y self.v_x = v_x self.v_y = v_y def move(self): self.x += self.v_x self.y += self.v_y if self.x < 0: self.x = WIDTH + self.x if self.y < 0: self.y = HEIGHT + self.y if self.x >= WIDTH: self.x -= WIDTH if self.y >= HEIGHT: self.y -= HEIGHT def __str__(self): return f"Robot: x={self.x}, y={self.y}, v_x={self.v_x}, v_y={self.v_y}" def __repr__(self): return self.__str__() def read_input() -> List[str]: with open(INPUT_FILE, "r") as f: return f.read().splitlines() def parse_input(input: List[str]) -> List[Robot]: robots: List[Robot] = [] for line in input: line = line.split(" ") pos = line[0][2:].split(",") x, y = int(pos[0]), int(pos[1]) velo = line[1][2:].split(",") v_x, v_y = int(velo[0]), int(velo[1]) robots.append(Robot(x, y, v_x, v_y)) return robots def predict(robots: List[Robot], seconds: int) -> List[Robot]: for i in range(seconds): for robot in robots: robot.move() return robots def print_grid(robots: List[Robot]): for y in range(HEIGHT): for x in range(WIDTH): r = 0 for robot in robots: if robot.x == x and robot.y == y: r += 1 if r == 0: print(".", end="") else: print(str(r), end="") print() def safety_score(robots: List[Robot]) -> int: quadrant_one = 0 quadrant_two = 0 quadrant_three = 0 quadrant_four = 0 for robot in robots : if robot.x < WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_one += 1 elif robot.x > WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_two += 1 elif robot.x < WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_three += 1 elif robot.x > WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_four += 1 return quadrant_one * quadrant_two * quadrant_three * quadrant_four def main(): robots = parse_input(read_input()) robots = predict(robots, 100) print(safety_score(robots)) if __name__ == "__main__": main()
python
2024
14
1
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
219150360
import re from functools import reduce from operator import mul result = 0 width = 101 height = 103 duration = 100 robots = [] with open("14_input.txt", "r") as f: for line in f: px, py, vx, vy = map(int, re.findall(r"(-?\d+)", line)) for sec in range(duration): px = (px + vx) % width py = (py + vy) % height robots.append((px, py)) q_width = width // 2 q_height = height // 2 quadrants = {0: 0, 1: 0, 2: 0, 3: 0} for robot in robots: if robot[0] < q_width: if robot[1] < q_height: quadrants[0] += 1 elif robot[1] > q_height: quadrants[1] += 1 elif robot[0] > q_width: if robot[1] < q_height: quadrants[2] += 1 elif robot[1] > q_height: quadrants[3] += 1 print(reduce(mul, quadrants.values()))
python
2024
14
2
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?
8053
from collections import defaultdict from statistics import stdev def read_input(file_path): """Read input from file and parse positions and velocities.""" positions, velocities = [], [] with open(file_path) as f: for line in f: p_sec, v_sec = line.split() positions.append([int(i) for i in p_sec.split("=")[1].split(",")]) velocities.append([int(i) for i in v_sec.split("=")[1].split(",")]) return positions, velocities def simulate_motion(positions, velocities, num_x=101, num_y=103, steps=10000): """Simulate motion and detect significant changes in distribution.""" for step in range(1, steps + 1): block_counts = defaultdict(int) new_positions = [] for pos, vel in zip(positions, velocities): new_x = (pos[0] + vel[0]) % num_x new_y = (pos[1] + vel[1]) % num_y new_positions.append([new_x, new_y]) block_counts[(new_x // 5, new_y // 5)] += 1 if stdev(block_counts.values()) > 3: print(step) break positions = new_positions if __name__ == "__main__": positions, velocities = read_input("input.txt") simulate_motion(positions, velocities)
python
2024
14
2
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?
8053
from collections import defaultdict from statistics import stdev with open("input.txt") as input_file: input_text = input_file.read().splitlines() num_x = 101 num_y = 103 initial_positions = [] velocities = [] for line in input_text: p_sec, v_sec = line.split() initial_positions.append([int(i) for i in p_sec.split("=")[1].split(",")]) velocities.append([int(i) for i in v_sec.split("=")[1].split(",")]) for counter in range(10000): block_counts = defaultdict(int) new_initial_positions = [] for initial_pos, velocity in zip(initial_positions, velocities): new_position = [ (initial_pos[0] + velocity[0]) % num_x, (initial_pos[1] + velocity[1]) % num_y, ] new_initial_positions.append(new_position) block_counts[(new_position[0] // 5, new_position[1] // 5)] += 1 if stdev(block_counts.values()) > 3: print(counter + 1) initial_positions = new_initial_positions
python
2024
14
2
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?
8053
import re; L = len(M:=[*map(int, re.findall('[-\d]+', open(0).read()))]) R, C = 103, 101; B = (1, -1) for T in range(R*C): G = [['.']*C for _ in range(R)] Z = [0]*4 for i in range(0, L, 4): py, px, vy, vx = M[i:i+4] x = (px+vx*T)%R; y = (py+vy*T)%C G[x][y] = '#' if x == R//2 or y == C//2: continue Z[(x<R//2)+2*(y<C//2)] += 1 S = '\n'.join(''.join(r) for r in G) t = B[0] while '#'*t in S: t += 1 if t > B[0]: B = (t, T) if T == 100: print('Part 1:', Z[0]*Z[1]*Z[2]*Z[3]) print('Part 2:', B[1])
python
2024
14
2
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?
8053
with open("Day-14-Challenge/input.txt", "r") as file: lines = file.readlines() WIDE = 101 TALL = 103 robots = [] for robot in lines: # format sides = robot.split(" ") left_side = sides[0] right_side = sides[1] left_sides = left_side.split(",") Px = left_sides[0].split("=")[-1] Py = left_sides[1] right_sides = right_side.split(",") Vx = right_sides[0].split("=")[-1] Vy = right_sides[1].strip() Px = int(Px) Py = int(Py) Vx = int(Vx) Vy = int(Vy) robots.append([Px,Py,Vx,Vy]) smallest_answer = 999999999999 found_at_second = 0 for second in range(WIDE * TALL): # pattern will repeat every WIDE * TALL times q1 = 0 q2 = 0 q3 = 0 q4 = 0 final_grid = [[0]*WIDE for _ in range(TALL)] for i in range(len(robots)): Px,Py,Vx,Vy = robots[i] new_Py, new_Px = (Px + Vx * second),(Py + Vy * second) # swap X and Y coords because its swapped in the examples too # for matplotlib new_Px, new_Py = (new_Px % TALL), (new_Py % WIDE) final_grid[new_Px][new_Py] += 1 vertical_middle = WIDE // 2 horizontal_middle = TALL // 2 if new_Px < vertical_middle and new_Py < horizontal_middle: q1 += 1 if new_Px > vertical_middle and new_Py < horizontal_middle: q2 += 1 if new_Px < vertical_middle and new_Py > horizontal_middle: q3 += 1 if new_Px > vertical_middle and new_Py > horizontal_middle: q4 += 1 answer = q1 * q2 * q3 * q4 # when answer is smallest, # robots are bunched together to draw the christmas tree, so one corner will have most robots # so when we multiply with other quadrants answer will be smaller # If we have 40 robots, answer is smaller if 37 are in Q1 and 1 each in rest = 37 # If they are evenly split its 10 * 10 * 10 * 10 = 10000 # So we assume that tree is drawn when smallest answer. # Mirrored approach doesnt work if(answer < smallest_answer): # find smallest answer smallest_answer = answer found_at_second = second print("Found smallest safety factor: ", smallest_answer) print("at second: ", found_at_second) # Total time complexity # O(WIDE * TALL * n) so kindof O(n) :) # Total space complexity # O(WIDE * TALL + n) so kindof O(n) :)
python
2024
14
2
--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have "improved" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?
8053
import pathlib import re import math lines = pathlib.Path("data.txt").read_text().split("\n") iterations = 100 width = 101 height = 103 robots = [] #example input only #width = 11 #height = 7 for line in lines: matches = re.findall(r"[-\d]+", line) x, y, vx, vy = [int(i) for i in matches] robots.append([x, y, vx, vy]) quadrants = [0, 0, 0, 0] for x, y, vx, vy in robots: x = (x + vx * iterations) % width y = (y + vy * iterations) % height mid_x = width//2 mid_y = height//2 if x < mid_x and y < mid_y: quadrants[0] += 1 elif x < mid_x and y > mid_y: quadrants[1] += 1 elif x > mid_x and y < mid_y: quadrants[2] += 1 elif x > mid_x and y > mid_y: quadrants[3] += 1 safety_factor = math.prod(quadrants) print(safety_factor) pictures = 0 for i in range(1, 100000): new_robots = [] board = [[0 for j in range(width)] for j in range(height)] for x, y, vx, vy in robots: x = (x + vx * i) % width y = (y + vy * i) % height new_robots.append((x, y)) board[y][x] = 1 if len(set(new_robots)) != len(new_robots): continue max_sum = max((sum(row) for row in board)) #the tree picture has 31 robots in a single row if max_sum > 30: print(i) break
python
2024
15
1
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?
1499739
def get_next(pos, move): move_dict = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith("#"): grid += [[c for c in line]] elif not line == "": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] == 'O': available = get_next((next_i, next_j), move) while grid[available[0]][available[1]] == 'O': available = get_next(available, move) if grid[available[0]][available[1]] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' grid[available[0]][available[1]] = 'O' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == 'O': total += 100 * i + j print(total)
python
2024
15
1
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?
1499739
pos = (0, 0) collision = {} directions = { '<': (-1, 0), '>': (1, 0), '^': (0, -1), 'v': (0, 1), } commands = [] def check_spot(position, directon): if (item := collision.get(position)) is None: return True if item == 'Wall': return False return item.can_move(directon) def can_move(position, direction): x, y = position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(position, direction): dir = directions[direction] return (position[0] + dir[0], position[1] + dir[1]) class Box: def __init__(self, x, y): self.x = x self.y = y @property def position(self): return (self.x, self.y) def can_move(self, direction): x, y = self.position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(self, direction): dir = directions[direction] collision[self.position] = None self.x += dir[0] self.y += dir[1] box = collision.get(self.position) if isinstance(box, Box): box.move(direction) collision[self.position] = self @property def score(self): return self.x + (self.y * 100) with open('input.txt') as f: has_read = False for yi, line in enumerate(f): if not has_read: for xi, c in enumerate(line): if len(line.strip()) == 0: has_read = True continue if not has_read: if c == '#': collision[(xi, yi)] = "Wall" elif c == '@': pos = (xi, yi) elif c == 'O': box = Box(xi, yi) collision[(xi, yi)] = box else: commands.append(line.strip()) commands = ''.join(commands) def print_grid(): mx, my = max(collision.keys()) grid = [['.'] * (mx + 1) for _ in range(my + 1)] for k, v in collision.items(): if v is None: continue x, y = k if v == 'Wall': grid[y][x] = '#' elif isinstance(v, Box): bx, by = v.position grid[by][bx] = 'O' grid[pos[1]][pos[0]] = '@' print('\n'.join(''.join(x) for x in grid)) for direction in commands: if can_move(pos, direction): pos = move(pos, direction) if isinstance(collision.get(pos), Box): collision[pos].move(direction) print_grid() boxes = set(collision[x] for x in collision if isinstance(collision[x], Box)) print(sum(x.score for x in boxes))
python
2024
15
1
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?
1499739
import re from typing import List, Tuple def parse_input(file_path: str) -> Tuple[List[List[str]], List[str]]: with open(file_path, 'r') as file: content = file.read().strip() grid_part, instructions_part = content.split('\n\n') grid = [list(line) for line in grid_part.split('\n')] instructions = list(''.join(instructions_part.split('\n'))) return grid, instructions def find_robot_position(grid: List[List[str]]) -> Tuple[int, int]: for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == '@': return x, y return -1, -1 def move_robot(grid: List[List[str]], instructions: List[str]) -> List[List[str]]: direction_map = { '^': (0, -1), 'v': (0, 1), '<': (-1, 0), '>': (1, 0) } x, y = find_robot_position(grid) for instruction in instructions: dx, dy = direction_map[instruction] new_x, new_y = x + dx, y + dy if not (0 <= new_x < len(grid[0]) and 0 <= new_y < len(grid)): continue if grid[new_y][new_x] == '#': continue elif grid[new_y][new_x] == 'O': # Check if we can push the box box_x, box_y = new_x, new_y while 0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid) and grid[box_y][box_x] == 'O': box_x += dx box_y += dy if not (0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid)) or grid[box_y][box_x] == '#': break else: # Move the robot and push the boxes while (box_x, box_y) != (new_x, new_y): box_x -= dx box_y -= dy grid[box_y + dy][box_x + dx] = 'O' grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y else: grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y return grid def calculate_gps_sum(grid: List[List[str]]) -> int: gps_sum = 0 for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == 'O': gps_sum += 100 * y + x return gps_sum if __name__ == "__main__": file_path = 'input.txt' grid, instructions = parse_input(file_path) print("Initial Grid:") for row in grid: print(''.join(row)) grid = move_robot(grid, instructions) print("\nFinal Grid:") for row in grid: print(''.join(row)) gps_sum = calculate_gps_sum(grid) print(f"\nSum of all boxes' GPS coordinates: {gps_sum}")
python
2024
15
1
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?
1499739
input = open("day_15\input.txt", "r").read().splitlines() warehouse_map = [] movements = "" cur_pos = (0,0) total = 0 movement_dict = { "v": (1, 0), "^": (-1, 0), ">": (0, 1), "<": (0, -1) } def find_open_spot(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == "#": return False elif pos_value == ".": return pos i = 0 while input[i] != "": if "@" in input[i]: cur_pos = (i, input[i].index("@")) warehouse_map.append(list(input[i])) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == "O": open_spot = find_open_spot(destination, movement_dict[move]) if open_spot: warehouse_map[open_spot[0]][open_spot[1]] = "O" warehouse_map[destination[0]][destination[1]] = "@" warehouse_map[cur_pos[0]][cur_pos[1]] = "." cur_pos = destination elif destination_value == ".": warehouse_map[destination[0]][destination[1]] = "@" warehouse_map[cur_pos[0]][cur_pos[1]] = "." cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == "O": total += 100 * i + j print(f"The sum of all boxes' GPS coordinates is {total}")
python
2024
15
1
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?
1499739
from collections import deque def find_start(grid, n, m): for i in range(n): for j in range(m): if grid[i][j] == '@': return (i, j) return (0, 0) def in_bounds(i, j, n, m): return (0 <= i < n) and (0 <= j < m) def move(grid, loc, dir, n, m): curr = (loc[0], loc[1]) addStack = deque() addStack.append('@') while True: newPos = (curr[0] + dir[0], curr[1] + dir[1]) if in_bounds(newPos[0], newPos[1], n, m): val = grid[newPos[0]][newPos[1]] if val == '#': return loc elif val == 'O': addStack.append('O') elif val == '.': revDir = (-dir[0], -dir[1]) while addStack: movedVal = addStack.pop() grid[newPos[0]] = grid[newPos[0]][:newPos[1]] + movedVal + grid[newPos[0]][newPos[1] + 1:] newPos = (newPos[0] + revDir[0], newPos[1] + revDir[1]) grid[loc[0]] = grid[loc[0]][:loc[1]] + '.' + grid[loc[0]][loc[1] + 1:] return (loc[0] + dir[0], loc[1] + dir[1]) else: return loc curr = (newPos[0], newPos[1]) def get_box_coords(grid, instructions): n = len(grid) m = len(grid[0]) loc = find_start(grid, n, m) dirMap = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} for instruction in instructions: loc = move(grid, loc, dirMap.get(instruction), n, m) total = 0 for i in range(n): for j in range(m): if grid[i][j] == 'O': total += ((100 * i) + j) return total if __name__ == "__main__": # Open file 'day15-1.txt' in read mode with open('day15-1.txt', 'r') as f: grid = [] ended = False instructions = [] for line in f: if line == '\n': ended = True line = line.strip() if not ended: grid.append(line) else: instructions.extend(list(line)) print("Final Coordinates of Boxes: " + str(get_box_coords(grid, instructions)))
python
2024
15
2
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### <vv<<^^<<^^ After appropriately resizing this map, the robot would push around these boxes as follows: Initial state: ############## ##......##..## ##..........## ##....[][]@.## ##....[]....## ##..........## ############## Move <: ############## ##......##..## ##..........## ##...[][]@..## ##....[]....## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[].@..## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.......@..## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##......@...## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.....@....## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##....@.....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##...@......## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##...@[]....## ##..........## ##..........## ############## Move ^: ############## ##...[].##..## ##...@.[]...## ##....[]....## ##..........## ##..........## ############## This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. ########## ##...[]... ##........ In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: #################### ##[].......[].[][]## ##[]...........[].## ##[]........[][][]## ##[]......[]....[]## ##..##......[]....## ##..[]............## ##..@......[].[][]## ##......[][]..[]..## #################### The sum of these boxes' GPS coordinates is 9021. Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
1522215
from dataclasses import dataclass @dataclass class Grid: grid: list[list[str]] robot_pos: tuple[int, int] = None def is_valid(self, x: int, y: int) -> bool: return 0 <= y < len(self.grid) and 0 <= x < len(self.grid[y]) def is_wall(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == "#" def is_box(self, x: int, y: int) -> bool: if self.is_valid(x, y): if self.grid[y][x] == "O": return True if self.grid[y][x] == "[" or self.grid[y][x] == "]": return True return False def is_empty(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == "." def get_robot_pos(self) -> tuple[int, int]: if self.robot_pos != None: return self.robot_pos for y in range(len(self.grid)): for x in range(len(self.grid[y])): if self.grid[y][x] == "@": self.set_robot_pos(x, y) return (x, y) return None def set_robot_pos(self, x: int, y: int): self.robot_pos = (x, y) def swap(self, x1: int, y1: int, x2: int, y2: int): if self.is_valid(x1, y1) and self.is_valid(x2, y2): temp = self.grid[y1][x1] self.grid[y1][x1] = self.grid[y2][x2] self.grid[y2][x2] = temp def __str__(self): out = "" for row in self.grid: line = "" for val in row: line += val out += line + "\n" return out def parse() -> tuple[Grid, str]: grid_input, moves = open("input.txt").read().split("\n\n") grid = Grid([[val for val in line] for line in grid_input.splitlines()]) return (grid, moves) def move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if move(grid, new_x, new_y, delta_x, delta_y): grid.swap(new_x, new_y, x, y) return True else: return False if grid.is_wall(new_x, new_y): return False return False def can_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): return True if grid.is_box(new_x, new_y): possible_to_move = False if delta_y != 0: if grid.grid[new_y][new_x] == "[": possible_to_move |= can_move(grid, new_x + 1, new_y, delta_x, delta_y) else: possible_to_move |= can_move(grid, new_x - 1, new_y, delta_x, delta_y) return possible_to_move and can_move(grid, new_x, new_y, delta_x, delta_y) else: return can_move(grid, new_x, new_y, delta_x, delta_y) if grid.is_wall(new_x, new_y): return False return False def wide_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if delta_y != 0: if grid.grid[new_y][new_x] == "[": wide_move(grid, new_x + 1, new_y, delta_x, delta_y) else: wide_move(grid, new_x - 1, new_y, delta_x, delta_y) wide_move(grid, new_x, new_y, delta_x, delta_y) grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): return False def part1(): grid, moves = parse() for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == ">" else -1 if robot_move == "<" else 0, 1 if robot_move == "v" else -1 if robot_move == "^" else 0) if move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) print(grid) coords = [100 * y + x if grid.is_box(x, y) else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) def part2(): grid, moves = parse() new_grid = [[]] for idx, row in enumerate(grid.grid): new_grid.append([]) for val in row: if val == "#": new_grid[idx].append("#") new_grid[idx].append("#") elif val == "O": new_grid[idx].append("[") new_grid[idx].append("]") elif val == ".": new_grid[idx].append(".") new_grid[idx].append(".") elif val == "@": new_grid[idx].append("@") new_grid[idx].append(".") grid.grid = new_grid for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == ">" else -1 if robot_move == "<" else 0, 1 if robot_move == "v" else -1 if robot_move == "^" else 0) if can_move(grid, x, y, delta_x, delta_y): if wide_move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) # print(grid) print(grid) coords = [100 * y + x if grid.grid[y][x] == "[" else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) part2()
python
2024
15
2
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### <vv<<^^<<^^ After appropriately resizing this map, the robot would push around these boxes as follows: Initial state: ############## ##......##..## ##..........## ##....[][]@.## ##....[]....## ##..........## ############## Move <: ############## ##......##..## ##..........## ##...[][]@..## ##....[]....## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[].@..## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.......@..## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##......@...## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.....@....## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##....@.....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##...@......## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##...@[]....## ##..........## ##..........## ############## Move ^: ############## ##...[].##..## ##...@.[]...## ##....[]....## ##..........## ##..........## ############## This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. ########## ##...[]... ##........ In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: #################### ##[].......[].[][]## ##[]...........[].## ##[]........[][][]## ##[]......[]....[]## ##..##......[]....## ##..[]............## ##..@......[].[][]## ##......[][]..[]..## #################### The sum of these boxes' GPS coordinates is 9021. Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
1522215
def get_next(pos, move): move_dict = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) def get_chars(c): if c == '@': return '@.' elif c == 'O': return '[]' else: return c + c def can_push(grid, pos, move): if move in ['<', '>']: next_pos = get_next(get_next(pos, move), move) if grid[next_pos[0]][next_pos[1]] == '.': return True if grid[next_pos[0]][next_pos[1]] in ['[', ']']: return can_push(grid, next_pos, move) return False if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '#' or grid[next_right[0]][next_right[1]] == '#': return False return (grid[next_left[0]][next_left[1]] == '.' or can_push(grid, next_left, move)) and (grid[next_right[0]][next_right[1]] == '.' or can_push(grid, next_right, move)) def push(grid, pos, move): if move in ['<', '>']: j = pos[1] while grid[pos[0]][j] != '.': _, j = get_next((pos[0], j), move) if j < pos[1]: grid[pos[0]][j:pos[1]] = grid[pos[0]][j+1:pos[1]+1] else: grid[pos[0]][pos[1]+1:j+1] = grid[pos[0]][pos[1]:j] if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '[': push(grid, next_left, move) else: if grid[next_left[0]][next_left[1]] == ']': push(grid, next_left, move) if grid[next_right[0]][next_right[1]] == '[': push(grid, next_right, move) grid[next_left[0]][next_left[1]] = '[' grid[next_right[0]][next_right[1]] = ']' grid[left[0]][left[1]] = '.' grid[right[0]][right[1]] = '.' def print_grid(grid): for line in grid: print("".join(line)) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith("#"): row = "" for c in line: row += get_chars(c) grid += [[c for c in row]] elif not line == "": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] in ['[', ']']: if can_push(grid, (next_i, next_j), move): push(grid, (next_i, next_j), move) grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '[': total += 100 * i + j print(total)
python
2024
15
2
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### <vv<<^^<<^^ After appropriately resizing this map, the robot would push around these boxes as follows: Initial state: ############## ##......##..## ##..........## ##....[][]@.## ##....[]....## ##..........## ############## Move <: ############## ##......##..## ##..........## ##...[][]@..## ##....[]....## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[].@..## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.......@..## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##......@...## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.....@....## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##....@.....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##...@......## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##...@[]....## ##..........## ##..........## ############## Move ^: ############## ##...[].##..## ##...@.[]...## ##....[]....## ##..........## ##..........## ############## This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. ########## ##...[]... ##........ In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: #################### ##[].......[].[][]## ##[]...........[].## ##[]........[][][]## ##[]......[]....[]## ##..##......[]....## ##..[]............## ##..@......[].[][]## ##......[][]..[]..## #################### The sum of these boxes' GPS coordinates is 9021. Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
1522215
def pprint(robot_x, robot_y, width, height): for y in range(height): for x in range(width): if (x, y) in walls: print("#", end="") elif (x, x + 1, y) in boxes: print("[]", end="") elif (x - 1, x, y) in boxes: continue elif robot_x == x and robot_y == y: print("@", end="") else: print(".", end="") print() def can_move(x, y, move, width, height, to_move): x += move[0] y += move[1] if x < 0 or x >= width or y < 0 or y >= height: return False if (x, y) in walls: return False # horizontal move: if move[1] == 0: # left move: if move[0] == -1: if (x + move[0], x, y) in boxes: # need to move (x + move[0], x, y) box to left to_move.add((x + move[0], x, y)) return can_move(x + move[0], y, move, width, height, to_move) # right move else: if (x, x + move[0], y) in boxes: to_move.add((x, x + move[0], y)) return can_move(x + move[0], y, move, width, height, to_move) # vertical move: if move[0] == 0: if (x - 1, x, y) in boxes: to_move.add((x - 1, x, y)) return can_move(x - 1, y, move, width, height, to_move) and can_move(x, y, move, width, height, to_move) if (x, x + 1, y) in boxes: to_move.add((x, x + 1, y)) return can_move(x, y, move, width, height, to_move) and can_move(x + 1, y, move, width, height, to_move) return True def move_robot(x, y, width, height): for move in moves: to_move = set() if can_move(x, y, move, width, height, to_move): for each in to_move: boxes.remove(each) for each in to_move: boxes.add((each[0] + move[0], each[1] + move[0], each[2] + move[1])) x += move[0] y += move[1] def main(): warehouse_done = False robot_x = 0 robot_y = 0 width = 0 height = 0 y = 0 with open("15_input.txt", "r") as f: for line in f: line = line.strip() if line != "": if warehouse_done: moves.extend([char_map[c] for c in line]) else: x = 0 for char in line: if char == '#': walls.append((x, y)) walls.append((x + 1, y)) elif char == "O": boxes.add((x, x + 1, y)) elif char == "@": robot_x = x robot_y = y x += 2 if x > width: width = x else: warehouse_done = True if not warehouse_done: y += 1 if y > height: height = y move_robot(robot_x, robot_y, width, height) result = 0 for box in boxes: result += 100 * box[2] + box[0] print(result) char_map = {"^": (0, -1), ">": (1, 0), "<": (-1, 0), "v": (0, 1)} walls = [] boxes = set() moves = [] if __name__ == "__main__": main()
python
2024
15
2
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### <vv<<^^<<^^ After appropriately resizing this map, the robot would push around these boxes as follows: Initial state: ############## ##......##..## ##..........## ##....[][]@.## ##....[]....## ##..........## ############## Move <: ############## ##......##..## ##..........## ##...[][]@..## ##....[]....## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[].@..## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.......@..## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##......@...## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.....@....## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##....@.....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##...@......## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##...@[]....## ##..........## ##..........## ############## Move ^: ############## ##...[].##..## ##...@.[]...## ##....[]....## ##..........## ##..........## ############## This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. ########## ##...[]... ##........ In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: #################### ##[].......[].[][]## ##[]...........[].## ##[]........[][][]## ##[]......[]....[]## ##..##......[]....## ##..[]............## ##..@......[].[][]## ##......[][]..[]..## #################### The sum of these boxes' GPS coordinates is 9021. Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
1522215
INPUT_FILE = "input.txt" WALL = "#" ROBOT = "@" BOX = "O" BOX_LEFT = "[" BOX_RIGHT = "]" MOVES = {"<": (-1, 0), ">": (1, 0), "^": (0, -1), "v": (0, 1)} class Warehouse: def __init__(self, width): self.width = width self.robot_location = (0, 0) self.walls = [] self.boxes = {} self.moves = [] def print(self): for y in range(self.height): for x in range(self.width): p = (x, y) if p == self.robot_location: print(ROBOT, end="") elif p in self.boxes: print(self.boxes[p], end="") elif p in self.walls: print(WALL, end="") else: print(".", end="") print() def add_wall(self, wall): wall_position = (wall[0] * 2, wall[1]) self.walls.append(wall_position) self.walls.append((wall_position[0] + 1, wall_position[1])) def add_box(self, box): box_position = (box[0] * 2, box[1]) self.boxes[box_position] = BOX_LEFT self.boxes[(box_position[0] + 1, box_position[1])] = BOX_RIGHT def set_robot_location(self, location): self.robot_location = (location[0] * 2, location[1]) def set_height(self, height): self.height = height def print_moves(self): for move in self.moves: print(move) def move(self, move): dx, dy = MOVES[move] new_location = (self.robot_location[0] + dx, self.robot_location[1] + dy) if new_location in self.walls: return if new_location in self.boxes: self.move_box(new_location, move) if new_location in self.boxes or new_location in self.walls: return self.robot_location = new_location def move_box(self, box, move): dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) # if horizontal if move == "<" or move == ">": if self.boxes[box] == BOX_RIGHT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_right != box_left: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT elif self.boxes[box] == BOX_LEFT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left != box_right: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT else: if self.collision_check(box, move): return False if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT return True def collision_check(self, box, move): collision = False dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) if new_box_left in self.walls or new_box_right in self.walls: return True if new_box_left in self.boxes: if self.collision_check(new_box_left, move): return True if new_box_right in self.boxes: if self.collision_check(new_box_right, move): return True return collision def run(self): for move in self.moves: self.move(move) def sum_of_box_locations(self): result = 0 for x, y in self.boxes: if self.boxes[(x, y)] == BOX_LEFT: result += x + 100 * y return result def read_file(): with open(INPUT_FILE, "r") as f: lines = f.readlines() width = len(lines[0].strip()) * 2 warehouse = Warehouse(width) moves = [] for y, line in enumerate(lines): if line[0] == "#": for x, c in enumerate(line.strip()): p = (x, y) if c == WALL: warehouse.add_wall(p) elif c == ROBOT: warehouse.set_robot_location(p) elif c == BOX: warehouse.add_box(p) elif line[0] == "\n": warehouse.set_height(y) else: for move in line.strip(): moves.append(move) warehouse.moves = moves return warehouse warehouse = read_file() warehouse.print() warehouse.run() print(warehouse.sum_of_box_locations())
python
2024
15
2
--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv< <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^>< ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v> v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### <vv<<^^<<^^ After appropriately resizing this map, the robot would push around these boxes as follows: Initial state: ############## ##......##..## ##..........## ##....[][]@.## ##....[]....## ##..........## ############## Move <: ############## ##......##..## ##..........## ##...[][]@..## ##....[]....## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[].@..## ##..........## ############## Move v: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.......@..## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##......@...## ############## Move <: ############## ##......##..## ##..........## ##...[][]...## ##....[]....## ##.....@....## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##....[]....## ##.....@....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##....@.....## ##..........## ############## Move <: ############## ##......##..## ##...[][]...## ##....[]....## ##...@......## ##..........## ############## Move ^: ############## ##......##..## ##...[][]...## ##...@[]....## ##..........## ##..........## ############## Move ^: ############## ##...[].##..## ##...@.[]...## ##....[]....## ##..........## ##..........## ############## This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. ########## ##...[]... ##........ In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: #################### ##[].......[].[][]## ##[]...........[].## ##[]........[][][]## ##[]......[]....[]## ##..##......[]....## ##..[]............## ##..@......[].[][]## ##......[][]..[]..## #################### The sum of these boxes' GPS coordinates is 9021. Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
1522215
input = open("day_15\input.txt", "r").read().splitlines() warehouse_map = [] movements = "" cur_pos = (0,0) total = 0 movement_dict = { "v": (1, 0), "^": (-1, 0), ">": (0, 1), "<": (0, -1) } def move_horizontally(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == "#": return False elif pos_value == ".": if move[1] == 1: warehouse_map[pos[0]][pos[1]] = "]" else: warehouse_map[pos[0]][pos[1]] = "[" while warehouse_map[pos[0]][pos[1] - move[1]] != "@": pos = (pos[0], pos[1] - move[1]) warehouse_map[pos[0]][pos[1]] = "]" if warehouse_map[pos[0]][pos[1]] == "[" else "[" return True def move_vertically(positions, move): involved_boxes = set(positions) next_positions = set(positions) while True: involved_boxes |= next_positions if len(next_positions) == 0: boxes_dict = {(x,y): warehouse_map[x][y] for (x,y) in involved_boxes} for box in involved_boxes: if not (box[0] - move[0], box[1]) in boxes_dict: warehouse_map[box[0]][box[1]] = "." warehouse_map[box[0] + move[0]][box[1]] = boxes_dict[box] return True positions = next_positions.copy() next_positions.clear() for pos in positions: next_pos = tuple(map(sum, zip(pos, move))) next_pos_value = warehouse_map[next_pos[0]][next_pos[1]] if next_pos_value == "[": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] + 1)) elif next_pos_value == "]": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] - 1)) elif next_pos_value == "#": return False i = 0 while input[i] != "": modified_input = [] for char in input[i]: if char == "#": modified_input += ["#", "#"] elif char == "O": modified_input += ["[", "]"] elif char == ".": modified_input += [".", "."] else: modified_input += ["@", "."] cur_pos = (i, modified_input.index("@")) warehouse_map.append(modified_input) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == "[" or destination_value == "]": if move == "<" or move == ">": open_spot = move_horizontally(destination, movement_dict[move]) else: if destination_value == "[": open_spot = move_vertically([destination, (destination[0], destination[1] + 1)], movement_dict[move]) else: open_spot = move_vertically([destination, (destination[0], destination[1] - 1)], movement_dict[move]) if open_spot: warehouse_map[destination[0]][destination[1]] = "@" warehouse_map[cur_pos[0]][cur_pos[1]] = "." cur_pos = destination elif destination_value == ".": warehouse_map[destination[0]][destination[1]] = "@" warehouse_map[cur_pos[0]][cur_pos[1]] = "." cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == "[": total += 100 * i + j print(f"The sum of all boxes' final GPS coordinates is {total}")
python
2024
16
1
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?
94444
from heapq import heappop, heappush def get_lowest_score(maze): m = len(maze) n = len(maze[0]) start = (-1, -1) end = (-1, -1) for i in range(m): for j in range(n): if maze[i][j] == 'S': start = (i, j) elif maze[i][j] == 'E': end = (i, j) maze[end[0]][end[1]] = '.' dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] visited = set() heap = [(0, 0, *start)] while heap: score, dI, i, j = heappop(heap) if (i, j) == end: break if (dI, i, j) in visited: continue visited.add((dI, i, j)) x = i + dirs[dI][0] y = j + dirs[dI][1] if maze[x][y] == '.' and (dI, x, y) not in visited: heappush(heap, (score + 1, dI, x, y)) left = (dI - 1) % 4 if (left, i, j) not in visited: heappush(heap, (score + 1000, left, i, j)) right = (dI + 1) % 4 if (right, i, j) not in visited: heappush(heap, (score + 1000, right, i, j)) return score if __name__ == "__main__": # Open file 'day16-1.txt' in read mode with open('day16-1.txt', 'r') as f: maze = [] for line in f: line = line.strip() maze.append(list(line)) print("Lowest Score:", get_lowest_score(maze))
python
2024
16
1
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?
94444
import heapq def dijkstra(grid): for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': start = ((i, j), (0, 1)) pq = [(0, start)] costs = { start: 0 } while len(pq) > 0: cost, (pos, direction) = heapq.heappop(pq) if grid[pos[0]][pos[1]] == 'E': return cost turns = [(1000, (pos, turn)) for turn in [(direction[1] * i, direction[0] * i) for i in [-1,1]]] step = tuple(map(sum, zip(pos, direction))) neighbors = turns + ([(1, (step, direction))] if grid[step[0]][step[1]] != '#' else []) for neighbor in neighbors: next_cost = cost + neighbor[0] if next_cost < costs.get(neighbor[1], float('inf')): heapq.heappush(pq, (next_cost, neighbor[1])) costs[neighbor[1]] = next_cost print("Could not find min path") return None with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] print(dijkstra(grid))
python
2024
16
1
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?
94444
# Python heap implementation from heapq import heappush, heappop with open("./day_16.in") as fin: grid = fin.read().strip().split("\n") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == "S": start = (i, j) elif grid[i][j] == "E": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # DIjkstra's q = [(0, 0, *start)] seen = set() while len(q) > 0: top = heappop(q) cost, d, i, j = top if (d, i, j) in seen: continue seen.add((d, i, j)) if grid[i][j] == "#": continue if grid[i][j] == "E": print(cost) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(cost + 1, d, ii, jj), (cost + 1000, (d + 1) % 4, i, j), (cost + 1000, (d + 3) % 4, i, j)]: if nbr[1:] in seen: continue heappush(q, nbr)
python
2024
16
1
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?
94444
import re from typing import List, Tuple import heapq def parse_input(file_path: str): """ Parse the input file to extract the data. Args: file_path (str): The path to the input file. Returns: List[str]: A list of strings representing the data from the file. """ with open(file_path, 'r') as file: return [line.strip() for line in file] def find_starting_position(grid: List[str]) -> Tuple[int, int]: """ Find the starting position marked as 'S' in the grid. Args: grid (List[str]): A list of strings representing the grid. Returns: Tuple[int, int]: A tuple containing the row and column indices of the starting position. """ for i, row in enumerate(grid): for j, cell in enumerate(row): if cell == 'S': return i, j return -1, -1 # given a grid and a current position as well as a direction, # return the list of next possible moves either moving forward in the current direction or turning left or right def get_possible_moves(grid: List[str], i: int, j: int, direction: str) -> List[Tuple[int, int, str]]: """ Get the possible moves from the current position in the grid. Args: grid (List[str]): A list of strings representing the grid. i (int): The row index of the current position. j (int): The column index of the current position. direction (str): The current direction ('N', 'E', 'S', 'W'). Returns: List[Tuple[int, int, str]]: A list of tuples where each tuple contains the row index, column index, and the direction of the possible moves. """ rows, cols = len(grid), len(grid[0]) moves = {'N': (-1, 0), 'E': (0, 1), 'S': (1, 0), 'W': (0, -1)} left_turns = {'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S'} right_turns = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'} possible_moves = [] # Check forward move dx, dy = moves[direction] new_i, new_j = i + dx, j + dy if 0 <= new_i < rows and 0 <= new_j < cols and grid[new_i][new_j] != '#': possible_moves.append((new_i, new_j, direction)) # Check left turn left_direction = left_turns[direction] left_dx, left_dy = moves[left_direction] left_i, left_j = i + left_dx, j + left_dy if 0 <= left_i < rows and 0 <= left_j < cols and grid[left_i][left_j] != '#': possible_moves.append((i, j, left_direction)) # Check right turn right_direction = right_turns[direction] right_dx, right_dy = moves[right_direction] right_i, right_j = i + right_dx, j + right_dy if 0 <= right_i < rows and 0 <= right_j < cols and grid[right_i][right_j] != '#': possible_moves.append((i, j, right_direction)) return possible_moves def find_lowest_score(grid: List[str], i: int, j: int, direction: str) -> int: """ Finds the shortest path in a grid from a starting position (i, j) in a given direction. Args: grid (List[str]): A 2D grid represented as a list of strings. i (int): The starting row index. j (int): The starting column index. direction (str): The initial direction of movement. Returns: int: The shortest path score to reach the target 'E' in the grid. If the target is not reachable, returns float('inf'). """ visited = set() heap = [(0, i, j, direction)] # (score, row, col, direction) while heap: score, i, j, direction = heapq.heappop(heap) if (i, j, direction) in visited: continue visited.add((i, j, direction)) if grid[i][j] == 'E': return score for new_i, new_j, new_direction in get_possible_moves(grid, i, j, direction): new_score = score + 1 if new_direction == direction else score + 1000 heapq.heappush(heap, (new_score, new_i, new_j, new_direction)) return float('inf') if __name__ == "__main__": file_path = 'input.txt' parsed_data = parse_input(file_path) i, j = find_starting_position(parsed_data) score = find_lowest_score(parsed_data, i, j, 'E') print(score)
python
2024
16
1
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?
94444
# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open("16.in") as fin: grid = fin.read().strip().split("\n") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == "S": start = (i, j) elif grid[i][j] == "E": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == "#": continue if grid[i][j] == "E": end_dir = d print(c) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr)
python
2024
16
2
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
502
# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open("16.in") as fin: grid = fin.read().strip().split("\n") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == "S": start = (i, j) elif grid[i][j] == "E": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == "#": continue if grid[i][j] == "E": end_dir = d break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr) # Go back through deps stack = [(end_dir, *end)] seen = set() seen_pos = set() while len(stack) > 0: top = stack.pop() if top in seen: continue seen.add(top) seen_pos.add(top[1:]) for nbr in deps[top]: stack.append(nbr) print(len(seen_pos))
python
2024
16
2
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
502
#d16 part 2 from heapq import heappop, heappush def part2(puzzle_input): grid = puzzle_input.split('\n') m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 'S': start = (i, j) elif grid[i][j] == 'E': end = (i, j) grid[end[0]] = grid[end[0]].replace('E', '.') def can_visit(d, i, j, score): prev_score = visited.get((d, i, j)) if prev_score and prev_score < score: return False visited[(d, i, j)] = score return True directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] heap = [(0, 0, *start, {start})] visited = {} lowest_score = None winning_paths = set() while heap: score, d, i, j, path = heappop(heap) if lowest_score and lowest_score < score: break if (i, j) == end: lowest_score = score winning_paths |= path continue if not can_visit(d, i, j, score): continue x = i + directions[d][0] y = j + directions[d][1] if grid[x][y] == '.' and can_visit(d, x, y, score+1): heappush(heap, (score + 1, d, x, y, path | {(x, y)})) left = (d - 1) % 4 if can_visit(left, i, j, score + 1000): heappush(heap, (score + 1000, left, i, j, path)) right = (d + 1) % 4 if can_visit(right, i, j, score + 1000): heappush(heap, (score + 1000, right, i, j, path)) return len(winning_paths) with open(r'16.txt','r') as f: input_text = f.read() res = part2(input_text) res
python
2024
16
2
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
502
import heapq from sys import maxsize maze = open("16.txt").read().splitlines() seen = [[[maxsize for _ in range(4)] for x in range(len(maze[0]))] for y in range(len(maze))] velocities = [(-1, 0), (0, 1), (1, 0), (0, -1)] start_pos = None end_pos = None for j, r in enumerate(maze): for i, c in enumerate(r): if c == 'S': start_pos = (j, i) if c == 'E': end_pos = (j, i) # TODO For C, need a better track of path than shoving it all into a list lmao # I saw on da reddit a lot of folks searching backwards through the maze scores # for all scores where score is -1 or -1001 from current, starting at end. pq = [(0, (*start_pos, 1), [start_pos])] # start facing EAST paths = [] best_score = maxsize while pq and pq[0][0] <= best_score: score, (y, x, dir), path = heapq.heappop(pq) if (y, x) == end_pos: best_score = score paths.append(path) continue if seen[y][x][dir] < score: continue seen[y][x][dir] = score for i in range(4): dy, dx = velocities[i] ny, nx = y + dy, x + dx if maze[ny][nx] != '#' and (ny, nx) not in path: cost = 1 if i == dir else 1001 heapq.heappush(pq, (score + cost, (ny, nx, i), path + [(ny, nx)])) seats = set() for path in paths: seats |= set(path) print(len(seats))
python
2024
16
2
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
502
import heapq from typing import Dict, List, Tuple class MinHeap: """ Min heap implementation using heapq library """ def __init__(self): self.heap = [] def insert(self, element: Tuple[int, str]): heapq.heappush(self.heap, element) def extract_min(self) -> Tuple[int, str]: return heapq.heappop(self.heap) def size(self) -> int: return len(self.heap) DIRECTIONS = [ {"x": 1, "y": 0}, {"x": 0, "y": 1}, {"x": -1, "y": 0}, {"x": 0, "y": -1}, ] def dijkstra( graph: Dict[str, Dict[str, int]], start: Dict[str, int], directionless: bool ) -> Dict[str, int]: queue = MinHeap() distances = {} starting_key = ( f"{start['x']},{start['y']},0" if not directionless else f"{start['x']},{start['y']}" ) queue.insert((0, starting_key)) distances[starting_key] = 0 while queue.size() > 0: current_score, current_node = queue.extract_min() if distances[current_node] < current_score: continue if current_node not in graph: continue for next_node, weight in graph[current_node].items(): new_score = current_score + weight if next_node not in distances or distances[next_node] > new_score: distances[next_node] = new_score queue.insert((new_score, next_node)) return distances def parse_grid(grid: List[str]): width, height = len(grid[0]), len(grid) start = {"x": 0, "y": 0} end = {"x": 0, "y": 0} forward = {} reverse = {} for y in range(height): for x in range(width): if grid[y][x] == "S": start = {"x": x, "y": y} if grid[y][x] == "E": end = {"x": x, "y": y} if grid[y][x] != "#": for i, direction in enumerate(DIRECTIONS): position = {"x": x + direction["x"], "y": y + direction["y"]} key = f"{x},{y},{i}" move_key = f"{position['x']},{position['y']},{i}" if ( 0 <= position["x"] < width and 0 <= position["y"] < height and grid[position["y"]][position["x"]] != "#" ): forward.setdefault(key, {})[move_key] = 1 reverse.setdefault(move_key, {})[key] = 1 for rotate_key in [ f"{x},{y},{(i + 3) % 4}", f"{x},{y},{(i + 1) % 4}", ]: forward.setdefault(key, {})[rotate_key] = 1000 reverse.setdefault(rotate_key, {})[key] = 1000 for i in range(len(DIRECTIONS)): key = f"{end['x']},{end['y']}" rotate_key = f"{end['x']},{end['y']},{i}" forward.setdefault(rotate_key, {})[key] = 0 reverse.setdefault(key, {})[rotate_key] = 0 return {"start": start, "end": end, "forward": forward, "reverse": reverse} def tilesApartFromMaze() -> int: with open("input.txt") as file: con = file.read() grid = con.strip().split("\n") parsed = parse_grid(grid) from_start = dijkstra(parsed["forward"], parsed["start"], False) to_end = dijkstra(parsed["reverse"], parsed["end"], True) end_key = f"{parsed['end']['x']},{parsed['end']['y']}" target = from_start[end_key] spaces = set() for position in from_start: if ( position != end_key and from_start[position] + to_end.get(position, float("inf")) == target ): x, y, *_ = position.split(",") # Unpack and ignore direction in the key spaces.add(f"{x},{y}") print(len(spaces)) tilesApartFromMaze()
python
2024
16
2
--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
502
import time from collections import deque POSSIBLE_DIRS = (1, -1, 1j, -1j) def calculate_min_scores( start: complex, walls: set[complex] ) -> dict[complex, dict[complex, int]]: scores = {1: {start: 0}, -1: {}, 1j: {}, -1j: {}} points = deque([(start, 1)]) while points: p, d = points.popleft() score = scores[d][p] for move, dir, cost in [(p + d, d, 1), (p, d * -1j, 1000), (p, d * 1j, 1000)]: if move in walls: continue if move in scores[dir] and scores[dir][move] <= score + cost: continue scores[dir][move] = score + cost points.append((move, dir)) return scores def parse(text: str): walls: set[complex] = set() start: complex = 0j end: complex = 0j for y, row in enumerate(text.splitlines()): for x, c in enumerate(row): match c: case "#": walls.add(complex(x, y)) case "S": start = complex(x, y) case "E": end = complex(x, y) case _: pass return start, end, walls def solve_part_2(text: str): start, end, walls = parse(text) scores = calculate_min_scores(start, walls) path: set[complex] = {start, end} cost = min(scores[dir][end] for dir in POSSIBLE_DIRS if end in scores[dir]) points = deque( [ (end, dir, cost) for dir in POSSIBLE_DIRS if end in scores[dir] and scores[dir][end] == cost ] ) while points: p, d, cost = points.popleft() for move, dir, c1 in [ (p - d, d, cost - 1), (p, d * 1j, cost - 1000), (p, d * -1j, cost - 1000), ]: if move in scores[dir] and scores[dir][move] == c1: path.add(move) points.append((move, dir, c1)) return len(path) if __name__ == "__main__": with open("input.txt", "r") as f: quiz_input = f.read() p_2_solution = int(solve_part_2(quiz_input))
python
2024
17
1
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
7,5,4,3,4,5,3,4,6
ADV = 0 BXL = 1 BST = 2 JNZ = 3 BXC = 4 OUT = 5 BDV = 6 CDV = 7 def get_combo_operand(operand, reg): if 0 <= operand <= 3: return operand if 4 <= operand <= 6: return reg[chr(ord('A') + operand - 4)] raise ValueError(f"Unexpected operand {operand}") with open('input.txt') as f: lines = f.read().splitlines() reg = { 'A': int(lines[0].split(": ")[1]), 'B': int(lines[1].split(": ")[1]), 'C': int(lines[2].split(": ")[1])} instructions = list(map(int, lines[4].split(": ")[1].split(","))) output = [] instr_ptr = 0 while instr_ptr < len(instructions): jump = False opcode, operand = instructions[instr_ptr:instr_ptr + 2] if opcode == ADV: reg['A'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == BXL: reg['B'] = reg['B'] ^ operand elif opcode == BST: reg['B'] = get_combo_operand(operand, reg) % 8 elif opcode == JNZ: if reg['A'] != 0: instr_ptr = operand jump = True elif opcode == BXC: reg['B'] = reg['B'] ^ reg['C'] elif opcode == OUT: output += [get_combo_operand(operand, reg) % 8] elif opcode == BDV: reg['B'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == CDV: reg['C'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) else: raise ValueError(f"Unexpected opcode {opcode}") if not jump: instr_ptr += 2 print(",".join(map(str, output)))
python
2024
17
1
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
7,5,4,3,4,5,3,4,6
from collections.abc import Generator def get_out(a: int) -> int: b = (a % 8) ^ 1 return (b ^ (a // 2**b) ^ 4) % 8 def get_all_out(a: int) -> list[int]: out: list[int] = [] while a > 0: out.append(get_out(a)) a = a // 8 return out def next_A(seq: int, a: int) -> Generator[int]: while True: out = get_out(a) if out == seq: yield a a += 1 def main() -> None: seq: list[int] = [0, 3, 5, 5, 3, 0, 4, 1, 7, 4, 5, 7, 1, 1, 4, 2] a: int = 0 steps: dict[int, Generator[int]] = {} i = 1 while True: if i == len(seq) + 1: break s = seq[i - 1] if i not in steps: steps[i] = next_A(s, a) a = next(steps[i]) out = get_all_out(a) if out == list(reversed(seq[:i])): i += 1 a *= 8 print(a // 8) if __name__ == "__main__": main()
python
2024
17
1
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
7,5,4,3,4,5,3,4,6
#!/usr/bin/python3 def combo_operand(op:int) -> int: combo_operands = {4:"A",5:"B",6:"C"} return op if op < 4 else registers[combo_operands[op]] def adv(op:int) -> int: return int(registers["A"] / 2 ** combo_operand(op)) def bxl(op:int) -> int: return registers["B"] ^ op def bst(op:int) -> int: return combo_operand(op) % 8 def jnz(inst_pointer:int, op:int) -> int: return op if registers["A"] != 0 else inst_pointer + 2 def bxc(op:int) -> int: return registers["B"] ^ registers["C"] def out(op:int) -> str: return str(combo_operand(op) % 8) def bdv(op:int) -> int: return adv(op) def cdv(op:int) -> int: return adv(op) with open("input.txt") as file: registers = {} for line in file: if "Register" in line: line = line.strip().split() registers[line[1].strip(":")] = int(line[2]) elif "Program" in line: line = line.strip("Program: ") program = [int(n) for n in line.strip().split(",")] instruction_pointer = 0 output = [] while instruction_pointer < len(program): opcode = program[instruction_pointer] operand = program[instruction_pointer + 1] if opcode == 0: registers["A"] = adv(operand) elif opcode == 1: registers["B"] = bxl(operand) elif opcode == 2: registers["B"] = bst(operand) elif opcode == 3: instruction_pointer = jnz(instruction_pointer, operand) continue elif opcode == 4: registers["B"] = bxc(operand) elif opcode == 5: output.append(out(operand)) elif opcode == 6: registers["B"] = bdv(operand) elif opcode == 7: registers["C"] = cdv(operand) instruction_pointer += 2 print("Program output:", ",".join(output))
python
2024
17
1
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
7,5,4,3,4,5,3,4,6
output = "" i = 0 def get_result_string(regs, instructions): global output n = len(instructions) global i def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 def adv(operand): operand = get_combo(operand) regs['a'] = int(regs['a'] // (2**operand)) return def bxl(operand): regs['b'] = int(regs['b'] ^ operand) return def bst(operand): operand = get_combo(operand) regs['b'] = int(operand % 8) return def jnz(operand): global i if regs['a'] != 0: i = int(operand) - 1 return def bxc(operand): regs['b'] = int(regs['b'] ^ regs['c']) return def out(operand): global output operand = get_combo(operand) output += str(operand % 8) return def bdv(operand): operand = get_combo(operand) regs['b'] = int(regs['a'] // (2**operand)) return def cdv(operand): operand = get_combo(operand) regs['c'] = int(regs['a'] // (2**operand)) return while i < n: curr = instructions[i] if curr[0] == 0: adv(curr[1]) elif curr[0] == 1: bxl(curr[1]) elif curr[0] == 2: bst(curr[1]) elif curr[0] == 3: jnz(curr[1]) elif curr[0] == 4: bxc(curr[1]) elif curr[0] == 5: out(curr[1]) elif curr[0] == 6: bdv(curr[1]) elif curr[0] == 7: cdv(curr[1]) i += 1 return ','.join(list(output)) if __name__ == "__main__": regs = {} instructions = [] # Open file 'day17-1.txt' in read mode with open('day17-1.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = int(line[line.find(':') + 2:]) elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] instructions = [(instructions[i], instructions[i + 1]) for i in range(0, len(instructions), 2)] print("Result String:", get_result_string(regs, instructions))
python
2024
17
1
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
7,5,4,3,4,5,3,4,6
import re instr_map = { 0: lambda operand: adv(operand), 1: lambda operand: bxl(operand), 2: lambda operand: bst(operand), 3: lambda operand: jnz(operand), 4: lambda operand: bxc(operand), 5: lambda operand: out(operand), 6: lambda operand: bdv(operand), 7: lambda operand: cdv(operand) } def combo(operand): global reg_a, reg_b, reg_c if 0 <= operand <= 3: return operand elif operand == 4: return reg_a elif operand == 5: return reg_b elif operand == 6: return reg_c def adv(operand): global reg_a reg_a = reg_a // (2 ** combo(operand)) def bxl(operand): global reg_b reg_b = reg_b ^ operand def bst(operand): global reg_b reg_b = combo(operand) % 8 def bxc(operand): global reg_b, reg_c reg_b = reg_b ^ reg_c def out(operand): print(f'{combo(operand) % 8},', end='') def bdv(operand): global reg_a, reg_b reg_b = reg_a // (2 ** combo(operand)) def cdv(operand): global reg_a, reg_c reg_c = reg_a // (2 ** combo(operand)) def jnz(operand): global ip, reg_a if reg_a != 0: ip = operand ip -= 2 def main(): global reg_a, reg_b, reg_c, ip with open("17_input.txt", "r") as f: reg_a = int(re.search(r"(\d+)", f.readline())[0]) reg_b = int(re.search(r"(\d+)", f.readline())[0]) reg_c = int(re.search(r"(\d+)", f.readline())[0]) f.readline() program = [int(opcode) for opcode in re.findall(r"(\d+)", f.readline())] print(f'{reg_a=}, {reg_b=}, {reg_c=}, {program=}') while 0 <= ip < len(program): instr_map[program[ip]](program[ip+1]) ip += 2 reg_a: int = 0 reg_b: int = 0 reg_c: int = 0 ip: int = 0 if __name__ == '__main__': main()
python
2024
17
2
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
164278899142333
def run(regs, instructions): n = len(instructions) i = 0 output = [] def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 while i < n: curr = instructions[i] operand = instructions[i + 1] if curr == 0: regs['a'] //= 2**get_combo(operand) elif curr == 1: regs['b'] ^= operand elif curr == 2: regs['b'] = get_combo(operand) % 8 elif curr == 3: if regs['a']: i = operand continue elif curr == 4: regs['b'] ^= regs['c'] elif curr == 5: output.append(get_combo(operand) % 8) elif curr == 6: regs['b'] = regs['a'] // 2**get_combo(operand) elif curr == 7: regs['c'] = regs['a'] // 2**get_combo(operand) i += 2 return list(output) def get_lowest_a(regs, instructions): regs['a'] = 0 j = 1 iFloor = 0 while j <= len(instructions) and j >= 0: regs['a'] <<= 3 for i in range(iFloor, 8): regsCopy = regs.copy() regsCopy['a'] += i if instructions[-j:] == run(regsCopy, instructions): break else: j -= 1 regs['a'] >>= 3 iFloor = regs['a'] % 8 + 1 regs['a'] >>= 3 continue j += 1 regs['a'] += i iFloor = 0 return regs['a'] if __name__ == "__main__": regs = {} instructions = [] # Open file 'day17-2.txt' in read mode with open('day17-2.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = 0 elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] print("Lowest value of Register A:", get_lowest_a(regs, instructions))
python
2024
17
2
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
164278899142333
from part1 import parse_input def run(program, regs): """ Executes a given program with specified registers. Args: program (list of int): A list of integers representing the program's opcodes and operands. regs (list of int): A list of initial values for the registers. Yields: int: The result of the operation specified by opcode 5, modulo 8. The program supports the following opcodes: 0: Divide the value in reg_a by 2 raised to the power of the value in the register specified by operand. 1: XOR the value in reg_b with the operand. 2: Set reg_b to the value in the register specified by operand, modulo 8. 3: If the value in reg_a is non-zero, set the instruction pointer to operand - 2. 4: XOR the value in reg_b with the value in reg_c. 5: Yield the value in the register specified by operand, modulo 8. 6: Set reg_b to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. 7: Set reg_c to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. """ reg_a, reg_b, reg_c = range(4, 7) ip = 0 combo = [0, 1, 2, 3, *regs] while ip < len(program): opcode, operand = program[ip:ip + 2] if opcode == 0: combo[reg_a] //= 2 ** combo[operand] elif opcode == 1: combo[reg_b] ^= operand elif opcode == 2: combo[reg_b] = combo[operand] % 8 elif opcode == 3: if combo[reg_a]: ip = operand - 2 elif opcode == 4: combo[reg_b] ^= combo[reg_c] elif opcode == 5: yield combo[operand] % 8 elif opcode == 6: combo[reg_b] = combo[reg_a] // (2 ** combo[operand]) elif opcode == 7: combo[reg_c] = combo[reg_a] // (2 ** combo[operand]) ip += 2 def expect(program, target_output, prev_a=0): """ Tries to find an integer 'a' such that when the 'program' is run with inputs derived from 'a', it produces the 'target_output' sequence. Args: program (iterable): The program to be run, which yields outputs based on inputs. target_output (list): The desired sequence of outputs that the program should produce. prev_a (int, optional): The previous value of 'a' used in the recursive calls. Defaults to 0. Returns: int or None: The integer 'a' that produces the 'target_output' when the program is run, or None if no such 'a' can be found. """ def helper(program, target_output, prev_a): if not target_output: return prev_a for a in range(1 << 10): if a >> 3 == prev_a & 127 and next(run(program, (a, 0, 0))) == target_output[-1]: result = helper(program, target_output[:-1], (prev_a << 3) | (a % 8)) if result is not None: return result return None return helper(program, target_output, prev_a) if __name__ == "__main__": file_path = 'input.txt' registers, program = parse_input(file_path) # Example target output target_output = program.copy() initial_value = expect(program, target_output) if initial_value is not None: print(f"The initial value for register A that produces the target output is: {initial_value}") else: print("No initial value found that produces the target output within the given attempts.")
python
2024
17
2
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
164278899142333
with open("input.txt") as input_file: input_text = input_file.read().splitlines() program = [int(x) for x in input_text[4].removeprefix("Program: ").split(",")] a = 0 position = 0 offsets = [0] while position < len(program): if program[-1 - position] == ((a % 8) ^ 5 ^ 6 ^ (a // (2 ** ((a % 8) ^ 5)))) % 8: a *= 8 position += 1 offsets.append(0) elif offsets[-1] < 7: a += 1 offsets[-1] += 1 else: while offsets[-1] >= 7 and position > 0: a //= 8 offsets.pop(-1) position -= 1 a += 1 offsets[-1] += 1 print(a // 8)
python
2024
17
2
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
164278899142333
import re with open("17.txt") as i: input = [x.strip() for x in i.readlines()] test_data = """Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0""".split("\n") # input = test_data a, b, c = 0, 0, 0 program = None for l in input: if l.startswith("Register "): r, v = re.match(r"Register (A|B|C): (\d+)", l).groups() if r == "A": a = int(v) elif r == "B": b = int(v) elif r == "C": c = int(v) elif l.startswith("Program: "): program = [int(x) for x in l[9:].split(",")] def run_program(program: list[int], aa: int, bb: int, cc: int) -> list[int]: output = [] a, b, c = aa, bb, cc ip = 0 while ip < len(program): i = program[ip] op = program[ip+1] cop = None if op == 4: cop = a elif op == 5: cop = b elif op == 6: cop = c else: cop = op if i == 0: # adv a = a // (2**cop) elif i == 1: # bxl b = b ^ op elif i == 2: #bst b = cop % 8 elif i == 3: # jnz if a != 0: ip = op continue elif i == 4: # bxc b = b ^ c elif i == 5: # out output.append(cop%8) elif i == 6: # bdv b = a // (2**cop) elif i == 7: # cdv c = a // (2**cop) ip += 2 return output current = len(program) solutions = [0] while current>0: next_solutions = [] for aa in solutions: for i in range(8): r = run_program(program, (aa<<3) | i, b, c) if r[0] == program[current-1]: next_solutions.append((aa << 3) | i) current = current - 1 solutions = next_solutions part2 = min(solutions) print(part2)
python
2024
17
2
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
164278899142333
# day 17 import os def reader(): return open(f"17.txt", 'r').read().splitlines() def simulate(program, A): l = [0, 1, 2, 3, A, 0, 0, -1] out = [] i = 0 while i < len(program): op = program[i] operand = program[i + 1] if op == 0: l[4] = int(l[4] / (2 ** l[operand])) elif op == 1: l[5] = l[5] ^ operand elif op == 2: l[5] = l[operand] % 8 elif op == 3: if l[4] != 0: i = operand continue elif op == 4: l[5] = l[5] ^ l[6] elif op == 5: out.append(l[operand] % 8) elif op == 6: l[5] = int(l[4] / (2 ** l[operand])) elif op == 7: l[6] = int(l[4] / (2 ** l[operand])) i += 2 return out def part2(): f = reader() program = list(map(int, f[4][(f[4].find(': ') + 2):].split(','))) def backtrack(A=0, j=-1): if -j > len(program): return A m = float('inf') for i in range(8): t = (A << 3) | i if simulate(program, t)[j:] == program[j:]: m = min(m, backtrack(t, j - 1)) return m print(backtrack()) part2()
python
2024
18
1
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?
506
from heapq import heapify, heappop, heappush with open("input.txt") as input_file: input_text = input_file.read().splitlines() grid_size = 70 num_fallen = 1024 bytes = set() for byte in input_text[:num_fallen]: byte_x, byte_y = byte.split(",") bytes.add((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while True: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: print(distance) break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position))
python
2024
18
1
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?
506
from collections import deque from typing import List, Tuple def parse_input(file_path: str) -> List[Tuple[int, int]]: """ Parses the input file and returns a list of tuples containing integer pairs. Args: file_path (str): The path to the input file. Returns: List[Tuple[int, int]]: A list of tuples, where each tuple contains two integers parsed from a line in the input file. Each line in the file should contain two integers separated by a comma. """ with open(file_path, 'r') as file: return [tuple(map(int, line.strip().split(','))) for line in file] def initialize_grid(size: int) -> List[List[str]]: """ Initializes a square grid of the given size with all cells set to '.'. Args: size (int): The size of the grid (number of rows and columns). Returns: List[List[str]]: A 2D list representing the initialized grid. """ return [['.' for _ in range(size)] for _ in range(size)] def simulate_falling_bytes(grid: List[List[str]], byte_positions: List[Tuple[int, int]], num_bytes: int): """ Simulates the falling of bytes in a grid. Args: grid (List[List[str]]): A 2D list representing the grid where bytes will fall. byte_positions (List[Tuple[int, int]]): A list of tuples representing the (x, y) positions of bytes. num_bytes (int): The number of bytes to simulate falling. Returns: None """ for x, y in byte_positions[:num_bytes]: grid[y][x] = '#' def find_shortest_path(grid: List[List[str]]) -> int: """ Finds the shortest path in a grid from the top-left corner to the bottom-right corner. The grid is represented as a list of lists of strings, where '.' represents an open cell and any other character represents an obstacle. Args: grid (List[List[str]]): The grid to search, where each element is a string representing a cell. Returns: int: The number of steps in the shortest path from the top-left to the bottom-right corner. Returns -1 if no such path exists. """ size = len(grid) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] queue = deque([(0, 0, 0)]) # (x, y, steps) visited = set([(0, 0)]) while queue: x, y, steps = queue.popleft() if (x, y) == (size - 1, size - 1): return steps for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < size and 0 <= ny < size and grid[ny][nx] == '.' and (nx, ny) not in visited: visited.add((nx, ny)) queue.append((nx, ny, steps + 1)) return -1 # No path found if __name__ == "__main__": file_path = 'input.txt' byte_positions = parse_input(file_path) grid_size = 71 # For the actual problem, use 71; for the example, use 7 grid = initialize_grid(grid_size) simulate_falling_bytes(grid, byte_positions, 1024) steps = find_shortest_path(grid) print(f"Minimum number of steps needed to reach the exit: {steps}")
python
2024
18
1
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?
506
from heapq import heappop, heappush def in_bounds(i, j, n): return 0 <= i < n and 0 <= j < n def navigate(maze, n): start = (0, 0) end = (n - 1, n - 1) heap = [(0, start[0], start[1])] visited = set() while heap: score, i, j = heappop(heap) if (i, j) == end: break if (i, j) in visited: continue visited.add((i, j)) if in_bounds(i, j+1, n) and maze[i][j+1] not in visited and maze[i][j+1] == '.': heappush(heap, (score + 1, i, j+1)) if in_bounds(i+1, j, n) and maze[i+1][j] not in visited and maze[i+1][j] == '.': heappush(heap, (score + 1, i+1, j)) if in_bounds(i, j-1, n) and maze[i][j-1] not in visited and maze[i][j-1] == '.': heappush(heap, (score + 1, i, j-1)) if in_bounds(i-1, j, n) and maze[i-1][j] not in visited and maze[i-1][j] == '.': heappush(heap, (score + 1, i-1, j)) return score def init_maze(bytes, n, numBytes): maze = [['.' for _ in range(n)] for _ in range(n)] for byte in bytes[:numBytes]: maze[byte[1]][byte[0]] = '#' return maze def get_min_steps(bytes): n = 71 numBytes = 1024 maze = init_maze(bytes, n, numBytes) return navigate(maze, n) if __name__ == "__main__": # Open file 'day18-1.txt' in read mode with open('day18-1.txt', 'r') as f: bytes = [] for line in f: line = line.strip() x, y = line.split(',') bytes.append((int(x), int(y))) print("Minimum steps:", get_min_steps(bytes))
python
2024
18
1
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?
506
def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) print("no path found") return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split(","))) for line in lines] x_len = 71 y_len = 71 print(len(bfs(set(byte_locs[0:1024]), x_len, y_len)) - 1)
python
2024
18
1
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?
506
from heapq import heappush, heappop with open("./day_18.in") as fin: lines = fin.read().strip().split("\n") coords = set([tuple(map(int, line.split(","))) for line in lines][:1024]) dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): print(cost[(i, j)]) break for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj))
python
2024
18
2
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)
62,6
from heapq import heapify, heappop, heappush with open("input.txt") as input_file: input_text = input_file.read().splitlines() grid_size = 70 bytes_list = [] for byte in input_text: byte_x, byte_y = byte.split(",") bytes_list.append((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) bytes_needed_lower = 0 bytes_needed_upper = len(bytes_list) - 1 while bytes_needed_lower < bytes_needed_upper: mid = (bytes_needed_lower + bytes_needed_upper) // 2 bytes = set(bytes_list[:mid]) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while discovered: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position)) else: bytes_needed_upper = mid continue bytes_needed_lower = mid + 1 print(",".join([str(x) for x in bytes_list[bytes_needed_lower - 1]]))
python
2024
18
2
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)
62,6
def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split(","))) for line in lines] x_len = 71 y_len = 71 lower = 0 upper = len(byte_locs) - 1 while lower <= upper: mid = (lower + upper) // 2 test = bfs(set(byte_locs[0:mid]), x_len, y_len) if test is None: upper = mid - 1 print("not reachable at", byte_locs[mid-1]) else: print("reachable at", byte_locs[mid-1]) lower = mid + 1 print(byte_locs[mid])
python
2024
18
2
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)
62,6
from heapq import heappush, heappop with open("./day_18.in") as fin: lines = fin.read().strip().split("\n") coords = [tuple(map(int, line.split(","))) for line in lines] dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def doable(idx): # Can we get to the index with first `idx` coords blocked? def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords[:idx] q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): return True for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj)) return False # Binary search for first coord that is not doable lo = 0 hi = len(coords) - 1 while hi > lo: mid = (lo + hi) // 2 if doable(mid): lo = mid + 1 else: hi = mid print(",".join(map(str, coords[lo-1])))
python
2024
18
2
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)
62,6
from collections import deque l = open("18.txt").read().splitlines() l = [list(map(int, x.split(","))) for x in l] max_x = max(coord[0] for coord in l) max_y = max(coord[1] for coord in l) def P2(): for find in range(1024,len(l)): grid = [["." for _ in range(max_y + 1)] for _ in range(max_x + 1)] for i in range(find): x,y = l[i] grid[x][y] = "#" def bfs(grid, start, end): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start, 0)]) visited = set() while queue: (x, y), dist = queue.popleft() if (x, y) == end: return dist if (x, y) in visited or grid[x][y] == "#": continue visited.add((x, y)) for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) not in visited: queue.append(((nx, ny), dist + 1)) return -1 if bfs(grid, (0,0), (max_x, max_y)) == -1: return l[find-1] print(P2())
python
2024
18
2
--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. "This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)
62,6
#!/usr/bin/env python3 import re from collections import defaultdict, deque myfile = open("18.in", "r") lines = myfile.read().strip().splitlines() myfile.close() blocks = [tuple(map(int, re.findall(r"\d+", line))) for line in lines] part_one = 0 part_two = 0 height = width = 70 def search(block_count): grid = defaultdict(str) for x in range(width + 1): for y in range(height + 1): grid[(x, y)] = "." grid[(width, height)] = "$" for x, y in blocks[: block_count + 1]: grid[(x, y)] = "" visited = set() scores = defaultdict(lambda: float("inf")) scores[(0, 0)] = 0 q = deque([(0, 0)]) while q: pos = q.popleft() visited.add(pos) if grid[pos] == "$": return scores[pos] next_score = scores[pos] + 1 for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: next_pos = (pos[0] + dir[0], pos[1] + dir[1]) if next_pos not in visited and next_score < scores[next_pos]: if grid[next_pos] != "": scores[next_pos] = next_score q.append(next_pos) return -1 unblocked, blocked = 1024, len(blocks) while blocked - unblocked > 1: mid = (unblocked + blocked) // 2 result = search(mid) if result == -1: blocked = mid else: unblocked = mid part_two = ",".join(map(str, blocks[blocked])) print("Part Two:", part_two)
python
2024
19
1
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?
267
from pprint import pprint WHITE = "w" BLUE = "u" BLACK = "b" RED = "r" GREEN = "g" INPUT_FILE = "test.txt" read_file = open(INPUT_FILE, "r") lines = read_file.readlines() available_towels = lines[0].strip().split(", ") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_word(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_word(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)
python
2024
19
1
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?
267
from functools import cache with open("input.txt") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split(", "): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return True patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return any(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))
python
2024
19
1
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?
267
def is_pattern_possible(pattern, towels, visited): if pattern == "": return True visited.add(pattern) return any([pattern.startswith(t) and pattern[len(t):] not in visited and is_pattern_possible(pattern[len(t):], towels, visited) for t in towels]) with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split(",")] patterns = lines[2:] print(sum([is_pattern_possible(p, towels, set()) for p in patterns]))
python
2024
19
1
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?
267
from pprint import pprint WHITE = "w" BLUE = "u" BLACK = "b" RED = "r" GREEN = "g" INPUT_FILE = "test.txt" read_file = open(INPUT_FILE, "r") lines = read_file.readlines() available_towels = lines[0].strip().split(", ") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_pattern(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_pattern(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)
python
2024
19
1
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?
267
with open("./day_19.in") as fin: lines = fin.read().strip().split("\n") units = lines[0].split(", ") designs = lines[2:] def possible(design): n = len(design) dp = [False] * len(design) for i in range(n): if design[:i+1] in units: dp[i] = True continue for u in units: if design[i-len(u)+1:i+1] == u and dp[i - len(u)]: # print(" ", i, u, design[-len(u):], dp[i - len(u)]) dp[i] = True break # print(design, dp) return dp[-1] ans = 0 for d in designs: if possible(d): print(d) ans += 1 print(ans)
python
2024
19
2
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?
796449099271652
def check_count(towels, pattern, cache): if pattern == "": return 1 if (block := cache.get(pattern, None)) is not None: return block result = 0 for towel in towels: if towel == pattern[:len(towel)]: result += check_count(towels, pattern[len(towel):], cache) cache[pattern] = result return result def get_num_achievable_patterns(towels, patterns): return sum([check_count(towels, pattern, {}) for pattern in patterns]) if __name__ == "__main__": towels = [] patterns = [] # Open file 'day19-2.txt' in read mode with open('day19-2.txt', 'r') as f: vals = [] for line in f: line = line.strip() if len(line) == 0: continue if len(towels) == 0: towels = line.split(', ') else: patterns.append(line) print("Number of ways to acheive patterns:", get_num_achievable_patterns(towels, patterns))
python
2024
19
2
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?
796449099271652
def num_possible_patterns(pattern, towels, memo): if pattern == "": return 1 if pattern in memo: return memo[pattern] res = sum([num_possible_patterns(pattern[len(t):], towels, memo) if pattern.startswith(t) else 0 for t in towels]) memo[pattern] = res return res with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split(",")] patterns = lines[2:] print(sum([num_possible_patterns(p, towels, dict()) for p in patterns]))
python
2024
19
2
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?
796449099271652
from functools import cache with open("input.txt") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split(", "): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return 1 patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return sum(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))
python
2024
19
2
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?
796449099271652
from typing import List, Tuple from collections import defaultdict from part1 import parse_input def count_ways_to_construct_design(design: str, towel_patterns: List[str]) -> int: """ Counts the number of ways to construct a given design using a list of towel patterns. Args: design (str): The design string that needs to be constructed. towel_patterns (List[str]): A list of towel patterns that can be used to construct the design. Returns: int: The number of ways to construct the design using the given towel patterns. """ n = len(design) dp = defaultdict(int) dp[0] = 1 # Base case: there's one way to construct an empty design for i in range(1, n + 1): for pattern in towel_patterns: if i >= len(pattern) and design[i - len(pattern):i] == pattern: dp[i] += dp[i - len(pattern)] return dp[n] def total_ways_to_construct_designs(towel_patterns: List[str], desired_designs: List[str]) -> int: """ Calculate the total number of ways to construct each design in the desired designs list using the given towel patterns. Args: towel_patterns (List[str]): A list of available towel patterns. desired_designs (List[str]): A list of desired designs to be constructed. Returns: int: The total number of ways to construct all the desired designs using the towel patterns. """ return sum(count_ways_to_construct_design(design, towel_patterns) for design in desired_designs) if __name__ == "__main__": file_path = 'input.txt' towel_patterns, desired_designs = parse_input(file_path) result = total_ways_to_construct_designs(towel_patterns, desired_designs) print(result)
python
2024
19
2
--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?
796449099271652
from collections import defaultdict def nb_possible_arrangements(design: str, towels: list[str]) -> int: cache: defaultdict[str, int] = defaultdict(lambda: 0) cache[""] = 1 for i in range(1, len(design) + 1): design_i = design[-i:] cache[design_i] = 0 for towel in towels: if design_i.startswith(towel): sub_design = design_i[len(towel) :] cache[design_i] += cache[sub_design] return cache[design] def main() -> None: towels: list[str] = [] designs: list[str] = [] with open("input.txt") as data: towels = data.readline().strip().split(", ") assert data.readline() == "\n" for line in data: designs.append(line.strip()) count = 0 for i, design in enumerate(designs): nb = nb_possible_arrangements(design, towels) count += nb print(count) if __name__ == "__main__": main()
python
2024
21
1
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
157908
from itertools import permutations keypadSequences = open('input.txt').read().splitlines() keypad = { '7': (0, 0), '8': (0, 1), '9': (0, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '1': (2, 0), '2': (2, 1), '3': (2, 2), '#': (3, 0), '0': (3, 1), 'A': (3, 2) } keypadBadPosition = (3,0) startKeypad = (3, 2) directionalpad = { '#': (0, 0), '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2) } directionalpadBadPosition = (0,0) startdirectionalpad = (0, 2) def getNumericPart(code): return ''.join([elem for elem in code if elem.isdigit()]) def getdirections(drow, dcol): res = [] if drow > 0: res.append('v'*drow) elif drow < 0: res.append('^'*abs(drow)) if dcol > 0: res.append('>'*dcol) elif dcol < 0: res.append('<'*abs(dcol)) return ''.join(res) def getPossiblePermutations(pos, directions, position): perms = set(permutations(directions)) validPerms = [] for perm in perms: if validatepath(pos, perm, position): validPerms.append(''.join(perm)) return validPerms def validatepath(pos, directions, position): _pos = pos for direction in directions: if direction == 'v': _pos = (_pos[0] + 1, _pos[1]) elif direction == '^': _pos = (_pos[0] - 1, _pos[1]) elif direction == '>': _pos = (_pos[0], _pos[1] + 1) elif direction == '<': _pos = (_pos[0], _pos[1] - 1) if _pos == position: return False return True def getDirectionToWriteCode(input): pos = startKeypad result = [] for elem in input: nextPos = keypad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, keypadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos return result def getDirectionToWriteDirection(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos min_length = min(len(r) for r in result) return [r for r in result if len(r) == min_length] def getDirectionToWriteDirectionSample(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0] result.append(validPaths) result.append('A') pos = nextPos return ''.join(result) def calculateComplexity(code): sol1 = getDirectionToWriteCode(code) sol2 = [elem for sol in sol1 for elem in getDirectionToWriteDirection(sol)] sol3 = [getDirectionToWriteDirectionSample(elem) for elem in sol2] print(sol3[0]) print(sol2[0]) print(sol1[0]) print(code) min_length = min(len(r) for r in sol3) num = getNumericPart(code) print(f"Code: Numeric: {num}, minimum length: {min_length}") return min_length * int(num) total = 0 for code in keypadSequences: score = calculateComplexity(code) total += score print() print(total) # <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A # <<vAA>A>^AvAA<^A>A<<vA>>^AvA^A<vA>^A<<vA>^A>AAvA^A<<vA>A>^AAAvA<^A>A # code = '029A' # sol1 = getDirectionToWriteCode(code) # sol2 = getDirectionToWriteDirection(sol1) # sol3 = getDirectionToWriteDirection(sol2) # print(sol3) # print(sol2) # print(sol1) # print(code) # print(calculateComplexity("029A"))
python
2024
21
1
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
157908
NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) path += [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] return "".join(path) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: l1 = get_shortest(NUMS, 'A' + line) l2 = get_shortest(ARROWS, 'A' + l1) l3 = get_shortest(ARROWS, 'A' + l2) total_complexity += int(line[0:-1]) * len(l3) print(total_complexity)
python
2024
21
1
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
157908
from abc import ABC import argparse from functools import cache from itertools import product from typing import Optional g_verbose = False CHR_A = ord('A') UP = ord('^') DOWN = ord('v') LEFT = ord('<') RIGHT = ord('>') CHR_0 = ord('0') CHR_1 = ord('1') CHR_2 = ord('2') CHR_3 = ord('3') CHR_4 = ord('4') CHR_5 = ord('5') CHR_6 = ord('6') CHR_7 = ord('7') CHR_8 = ord('8') CHR_9 = ord('9') def get_dir_h(dx: int) -> int: return LEFT if dx < 0 else RIGHT def get_dir_v(dy: int) -> int: return UP if dy < 0 else DOWN class RobotPad(ABC): id: int = 0 dir_cache: dict[tuple[int, int], list[list[int]]] pos_cache: dict[tuple[int, int], int] child: Optional['RobotPad'] = None @cache def cost_press_once(self, snapshot: tuple[int, ...]): my_id = self.id if not self.child: assert len(snapshot) == 1 return 1, snapshot g_verbose and print(f'{" " * my_id}bot #{my_id} request parent press') cost_moving, new_snapshot = self.child.cost_moving(CHR_A, snapshot[1:]) cost_press, new_snapshot = self.child.cost_press_once(new_snapshot) return cost_moving + cost_press, (snapshot[0], *new_snapshot) @cache def cost_moving(self, target_button: int, snapshot: tuple[int, ...]): my_id = self.id current_button = snapshot[0] g_verbose and print(f'{" " * my_id}bot #{my_id} plan {chr(current_button)} -> {chr(target_button)}') if current_button == target_button: g_verbose and print(f'{" " * my_id}bot #{my_id} not moving, already at {chr(target_button)}') return 0, snapshot # Last layer distance = self.pos_cache[current_button, target_button] if not self.child: g_verbose and print(f'{" " * my_id}bot #{my_id} move to {chr(target_button)}, cost={distance}') assert len(snapshot) == 1 return distance, (target_button,) # Move parent node to the direction I want tracking = [] for possible_routes in self.dir_cache[current_button, target_button]: route_cost = 0 route_snapshot = snapshot[1:] for next_direction in possible_routes: cost_moving, route_snapshot = self.child.cost_moving(next_direction, route_snapshot) cost_press, route_snapshot = self.child.cost_press_once(route_snapshot) route_cost += cost_moving + cost_press tracking.append((route_cost, (target_button, *route_snapshot))) best_cost, best_snapshot = min(tracking, key=lambda x: x[0]) g_verbose and print(f'{" " * my_id}bot #{my_id} move to {chr(target_button)}, cost={best_cost}') return best_cost, best_snapshot def move(self, dst: int, snapshot: tuple[int, ...]): return self.cost_moving(dst, snapshot) class NumPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x37, 0x38, 0x39], [0x34, 0x35, 0x36], [0x31, 0x32, 0x33], [0x00, 0x30, 0x41] ] self.pos_cache = {} self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): if a == b: continue # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a in (CHR_0, CHR_A) and b in (CHR_1, CHR_4, CHR_7): # Can only move up and then left dir_cache[a, b] = [[UP] * y_count + [LEFT] * x_count] elif a in (CHR_1, CHR_4, CHR_7) and b in (CHR_0, CHR_A): # Can only move right and then down dir_cache[a, b] = [[RIGHT] * x_count + [DOWN] * y_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.pos_cache[a, b] = abs(dx) + abs(dy) self.dir_cache = dir_cache class DirectionPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x00, UP, CHR_A], [LEFT, DOWN, RIGHT], ] self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} self.pos_cache = {} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 self.pos_cache[a, b] = abs(dx) + abs(dy) x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a == LEFT and b in (UP, CHR_A): # Can only move right and then UP dir_cache[a, b] = [[RIGHT] * x_count + [UP] * y_count] elif a in (UP, CHR_A) and b == LEFT: # Can only move down and then left dir_cache[a, b] = [[DOWN] * y_count + [LEFT] * x_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.dir_cache = dir_cache def solve_ex(codes: list[str], count: int) -> int: root = NumPad(0) node = root for i in range(count): bot = DirectionPad(i + 1) node.child = bot node = bot snapshot_init = tuple([CHR_A] * (count + 1)) result = 0 for code in codes: snapshot = snapshot_init total_cost = 0 for current_chr in map(ord, code): prev_char = snapshot[0] cost, snapshot = root.cost_moving(current_chr, snapshot) cost_press, snapshot = root.cost_press_once(snapshot) g_verbose and print( f"** move {chr(prev_char)} -> {chr(current_chr)} cost={cost + cost_press} pos={''.join(map(chr, snapshot))}") total_cost += cost + cost_press numeric_part = int(code[:-1]) print(f"{code} -> {total_cost} * {numeric_part}") result += total_cost * numeric_part return result def solve(input_path: str, /, **_kwargs): with open(input_path, "r", encoding='utf-8') as file: input_text = file.read().strip().replace('\r', '').splitlines() p1 = solve_ex(input_text, 2) print(f'p1: {p1}') def main(): global g_verbose parser = argparse.ArgumentParser() parser.add_argument("input", nargs="?", default="sample.txt") parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("--threshold", type=int, default=50, help="Threshold (p2)") args = parser.parse_args() g_verbose = args.verbose solve(args.input) if __name__ == "__main__": main()
python
2024
21
1
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
157908
import functools from typing import List, Tuple, Optional # Define the number pad and the direction pad number_pad = [ "789", "456", "123", " 0A" ] direction_pad = [ " ^A", "<v>" ] def parse_input(file_path: str) -> List[Tuple[str, int]]: """ Parses the input file and returns a list of tuples. Each tuple contains a string (the stripped line) and an integer (the first three characters of the line). Args: file_path (str): The path to the input file. Returns: List[Tuple[str, int]]: A list of tuples where each tuple contains a string and an integer. """ with open(file_path) as file: return [(line.strip(), int(line[:3])) for line in file] def find_position(pad: List[str], char: str) -> Optional[Tuple[int, int]]: """ Find the position of a character in a 2D list (pad). Args: pad (List[str]): A 2D list representing the pad where each element is a string. char (str): The character to find in the pad. Returns: Optional[Tuple[int, int]]: A tuple containing the x and y coordinates of the character if found, otherwise None. """ for y, row in enumerate(pad): for x, cell in enumerate(row): if cell == char: return x, y return None def generate_path(pad: List[str], from_char: str, to_char: str) -> str: """ Generate the shortest path from `from_char` to `to_char` in the given pad. The path is represented as a string of direction changes: - '<' for left - '>' for right - '^' for up - 'v' for down - 'A' for arrival at the target position Args: pad (List[str]): A 2D list representing the pad where each element is a character. from_char (str): The character representing the starting position. to_char (str): The character representing the target position. Returns: str: The shortest path from `from_char` to `to_char` based on the number of direction changes. """ from_x, from_y = find_position(pad, from_char) to_x, to_y = find_position(pad, to_char) def move(x: int, y: int, path: str): # If the current position is the target position, yield the path with 'A' appended if (x, y) == (to_x, to_y): yield path + 'A' # Move left if possible and the target is to the left if to_x < x and pad[y][x - 1] != ' ': yield from move(x - 1, y, path + '<') # Move up if possible and the target is above if to_y < y and pad[y - 1][x] != ' ': yield from move(x, y - 1, path + '^') # Move down if possible and the target is below if to_y > y and pad[y + 1][x] != ' ': yield from move(x, y + 1, path + 'v') # Move right if possible and the target is to the right if to_x > x and pad[y][x + 1] != ' ': yield from move(x + 1, y, path + '>') # Return the shortest path based on the number of direction changes return min(move(from_x, from_y, ""), key=lambda p: sum(a != b for a, b in zip(p, p[1:]))) @functools.lru_cache(None) def solve(sequence: str, level: int, max_level: int = 2) -> int: """ Solve the problem recursively. Args: sequence (str): The input sequence to process. level (int): The current recursion level. max_level (int, optional): The maximum recursion depth. Defaults to 2. Returns: int: The result of the recursive computation. """ if level > max_level: return len(sequence) pad = direction_pad if level else number_pad return sum(solve(generate_path(pad, from_char, to_char), level + 1, max_level) for from_char, to_char in zip('A' + sequence, sequence)) if __name__ == "__main__": input_data = parse_input('input.txt') result = sum(solve(sequence, 0) * multiplier for sequence, multiplier in input_data) print(result)
python
2024
21
1
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
157908
from functools import cache with open("input.txt") as input_file: input_text = input_file.read().splitlines() @cache def num_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = ">" if end[0] > start[0] else "<" vert_char = "v" if end[1] > start[1] else "^" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (0, 0) and path[:3] == ("v", "v", "v")) or (start == (0, 1) and path[:2] == ("v", "v")) or (start == (0, 2) and path[:1] == ("v",)) or (start == (1, 3) and path[:1] == ("<",)) or (start == (2, 3) and path[:2] == ("<", "<")) ): output.append(list(path) + ["A"]) return output @cache def dir_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = ">" if end[0] > start[0] else "<" vert_char = "v" if end[1] > start[1] else "^" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (1, 0) and path[:1] == ("<",)) or (start == (2, 0) and path[:2] == ("<", "<")) or (start == (0, 1) and path[:1] == ("^",)) ): output.append(list(path) + ["A"]) return output num_keypad = { "7": (0, 0), "8": (1, 0), "9": (2, 0), "4": (0, 1), "5": (1, 1), "6": (2, 1), "1": (0, 2), "2": (1, 2), "3": (2, 2), "0": (1, 3), "A": (2, 3), } directional_keypad = {"^": (1, 0), "A": (2, 0), "<": (0, 1), "v": (1, 1), ">": (2, 1)} total = 0 for code in input_text: current_pos = (2, 3) solutions = [[]] for character in code: new_pos = num_keypad[character] solutions = [ solution + path for solution in solutions for path in num_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer = [] for solution in solutions: current_pos = (2, 0) solutions_2 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_2 = [ partial_solution + path for partial_solution in solutions_2 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer += solutions_2 solutions_3_outer = [] for solution in solutions_2_outer: current_pos = (2, 0) solutions_3 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_3 = [ partial_solution + path for partial_solution in solutions_3 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_3_outer += solutions_3 total += min(len(x) for x in solutions_3_outer) * int(code[:3]) print(total)
python
2024
21
2
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
196910339808654
import sys from collections import Counter from functools import cache def test_input(): _input = """029A 980A 179A 456A 379A""".strip().split('\n') assert part_1(_input) == 126384 class Pad: LOOKUPS = {} def inputs(self, sequence: str): inputs = [] def _inputs(result, current, sequence): if len(sequence) == 0: inputs.append(result) return for move in self._inputs(current, sequence[0]): _inputs(result + move, sequence[0], sequence[1:]) _inputs('', 'A', sequence) return inputs def _inputs(self, start: str, end: str): sx, sy = self.LOOKUPS[start] ex, ey = self.LOOKUPS[end] dx, dy = ex - sx, ey - sy x_str = '<' * -dx if dx < 0 else '>' * dx y_str = '^' * -dy if dy < 0 else 'v' * dy value = [] if dy != 0 and (sx, sy + dy) != self.LOOKUPS[' ']: value.append(f'{y_str}{x_str}A') if dx != 0 and (sx + dx, sy) != self.LOOKUPS[' ']: value.append(f'{x_str}{y_str}A') if dx == dy == 0: value.append('A') return value class Numpad(Pad): """ A class representing a numpad with a specific layout. The numpad layout is as follows: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Attributes: LOOKUPS (dict): A dictionary containing lookup values for the numpad. """ LOOKUPS = { '7': (0, 0), '8': (1, 0), '9': (2, 0), '4': (0, 1), '5': (1, 1), '6': (2, 1), '1': (0, 2), '2': (1, 2), '3': (2, 2), ' ': (0, 3), '0': (1, 3), 'A': (2, 3), } class Dirpad(Pad): """ A class representing a direction pad with a specific layout. The direction pad layout is as follows: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ Attributes: LOOKUPS (dict): A dictionary containing lookup values for the direction pad. """ LOOKUPS = { ' ': (0, 0), '^': (1, 0), 'A': (2, 0), '<': (0, 1), 'v': (1, 1), '>': (2, 1), } def read_input(path: str) -> list[str]: with open(path) as input_file: return [line.strip() for line in input_file] @cache def shortest(sequence: str, depth: int): dirpad = Dirpad() if depth == 0: return len(sequence) total = 0 for sub in sequence.split('A')[:-1]: sequences = dirpad.inputs(sub + 'A') total += min(shortest(seq, depth - 1) for seq in sequences) return total def score_at_depth(input_data: list[str], depth: int) -> int: total = 0 numpad = Numpad() for code in input_data: numcode = numpad.inputs(code) min_len = min(shortest(nc, depth) for nc in numcode) total += min_len * int(code[:-1]) return total def part_1(input_data: list[str]) -> int: return score_at_depth(input_data, 2) def part_2(input_data: list[str]) -> int: return score_at_depth(input_data, 25) def main(): input_data = read_input(sys.argv[1]) print(f'Part 1: {part_1(input_data)}') print(f'Part 2: {part_2(input_data)}') if __name__ == '__main__': main()
python
2024
21
2
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
196910339808654
from collections import defaultdict, Counter NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } memo = dict() def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) to_append = [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] path += to_append return "".join(path).split("A")[0:-1] def count_parts(path): return Counter([s +"A" for s in path]) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: counts = count_parts(get_shortest(NUMS, 'A' + line)) for i in range(25): next_counts = defaultdict(int) for seq, count in counts.items(): for k, v in count_parts(get_shortest(ARROWS, 'A' + seq)).items(): next_counts[k] += count * v counts = next_counts length = sum([len(k) * v for k, v in counts.items()]) total_complexity += int(line[0:-1]) * length print(total_complexity)
python
2024
21
2
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
196910339808654
import functools with open("21.txt") as i: input = [x.strip() for x in i.readlines()] test_data = """029A 980A 179A 456A 379A""".split("\n") # input = test_data # +---+---+---+ # | 7 | 8 | 9 | # +---+---+---+ # | 4 | 5 | 6 | # +---+---+---+ # | 1 | 2 | 3 | # +---+---+---+ # | 0 | A | # +---+---+ numeric_keys = { "7": (0, 0), "8": (1, 0), "9": (2, 0), "4": (0, 1), "5": (1, 1), "6": (2, 1), "1": (0, 2), "2": (1, 2), "3": (2, 2), "0": (1, 3), "A": (2, 3), } # +---+---+ # | ^ | A | #+---+---+---+ #| < | v | > | #+---+---+---+ directional_keys = { "^": (1, 0), "A": (2, 0), "<": (0, 1), "v": (1, 1), ">": (2,1) } allowed_num_pos = [v for v in numeric_keys.values()] allowed_dir_pos = [v for v in directional_keys.values()] pos = (2,3) x, y = pos def find_keystrokes(src, target, directional): if src == target: return ["A"] if not directional and not src in allowed_num_pos: return [] if directional and not src in allowed_dir_pos: return [] x1, y1 = src x2, y2 = target res = [] if x1<x2: res.extend([">"+s for s in find_keystrokes((x1+1, y1), target, directional)]) elif x1>x2: res.extend(["<"+s for s in find_keystrokes((x1-1, y1), target, directional)]) if y1<y2: res.extend(["v"+s for s in find_keystrokes((x1, y1+1), target, directional)]) elif y1>y2: res.extend(["^"+s for s in find_keystrokes((x1, y1-1), target, directional)]) return res @functools.cache def find_shortest_to_click(a, b, depth=2): # Assume we start at A always? opts = find_keystrokes(directional_keys[a], directional_keys[b], True) if depth == 1: return min([len(x) for x in opts]) tmps = [] for o in opts: tmp = [] tmp.append(find_shortest_to_click("A", o[0], depth-1)) for i in range(1, len(o)): tmp.append(find_shortest_to_click(o[i-1], o[i], depth-1)) tmps.append(sum(tmp)) return min(tmps) def find_shortest(code, levels): pos = numeric_keys["A"] shortest = 0 for key in code: possible_key_sequences = find_keystrokes(pos, numeric_keys[key], False) tmps = [] for sequence in possible_key_sequences: tmp = [] tmp.append(find_shortest_to_click("A", sequence[0], levels)) for i in range(1, len(sequence)): tmp.append(find_shortest_to_click(sequence[i-1], sequence[i], levels)) tmps.append(sum(tmp)) pos = numeric_keys[key] shortest += min(tmps) return shortest def find_total_complexity(codes, levels): complexities = [] for code in input: s = find_shortest(code, levels) complexities.append(s*int(code[:-1])) return sum(complexities) print(find_total_complexity(input, 25))
python
2024
21
2
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
196910339808654
#!/usr/bin/env python3 import re from collections import deque from itertools import product myfile = open("21.in", "r") lines = myfile.read().strip().splitlines() myfile.close() part_two = 0 # fmt: off num_pad = { (0, 0): "7", (1, 0): "8", (2, 0): "9", (0, 1): "4", (1, 1): "5", (2, 1): "6", (0, 2): "1", (1, 2): "2", (2, 2): "3", (1, 3): "0", (2, 3): "A", } num_pad_t = {v: k for k, v in num_pad.items()} dir_pad = { (1, 0): "^", (2, 0): "A", (0, 1): "<", (1, 1): "v", (2, 1): ">", } dir_pad_t = {v: k for k, v in dir_pad.items()} # fmt: on button_dirs = {"<": (-1, 0), ">": (1, 0), "^": (0, -1), "v": (0, 1)} def dfs(start, end, use_dir_pad=True): key_pad = dir_pad if use_dir_pad else num_pad sequences = set() seen = set() q = deque([("", start)]) while q: sequence, pos = q.popleft() seen.add(pos) if pos == end: sequences.add(sequence + "A") continue buttons = ["<", "^", "v", ">"] for btn in buttons: d_x, d_y = button_dirs[btn] next_pos = (pos[0] + d_x, pos[1] + d_y) if next_pos not in seen and next_pos in key_pad: q.append((sequence + btn, next_pos)) min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} def get_sequences(sequence, use_dir_pad=True): key_pad_t = dir_pad_t if use_dir_pad else num_pad_t sub_sequences = [] start = key_pad_t["A"] for c in sequence: end = key_pad_t[c] sub_sequences.append(dfs(start, end, use_dir_pad)) start = end sequences = {"".join(x) for x in product(*sub_sequences)} min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} memo = {} def solve(sequence, robots, is_code=False): if robots == 0: return len(sequence) if (sequence, robots) not in memo: total = 0 sub_sequences = list(re.findall(r".*?A", sequence)) for sub_seq in sub_sequences: total += min( solve(s, robots - 1) for s in get_sequences(sub_seq, not is_code) ) memo[(sequence, robots)] = total return memo[(sequence, robots)] for code in lines: numeric_code = int(code[:-1]) part_two += solve(code, 26, is_code=True) * numeric_code print("Part Two:", part_two)
python
2024
21
2
--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A v<<A>>^A<A>AvA<^AA>A<vAAA>^A <A^A>^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
196910339808654
#day 21 import os from itertools import pairwise from functools import cache def reader(): return open(f"input.txt", 'r').read().splitlines() def getPT(G, chars): P = {c: (i, j) for i, r in enumerate(G) for j, c in enumerate(r)} T = {c1: {c2: set() for c2 in chars} for c1 in chars} for c1 in T: for c2 in T[c1]: (x1, y1), (x2, y2) = P[c1], P[c2] v, vc = 'v' if x1 < x2 else '^', abs(x2 - x1) h, hc = '>' if y1 < y2 else '<', abs(y2 - y1) if G[x1][y2] in chars: T[c1][c2].add(h * hc + v * vc) if G[x2][y1] in chars: T[c1][c2].add(v * vc + h * hc) return P, T def part2(): f = reader() G0 = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['#', '0', 'A'], ] GC = [ ['#', '^', 'A'], ['<', 'v', '>'] ] _, G0T = getPT(G0, '0123456789A') _, GCT = getPT(GC, '<^>vA') def r(T, s, i=0, c='A'): return [[t1] + t2 for t1 in T[c][s[i]] for t2 in r(T, s, i + 1, s[i])] if i < len(s) else [[]] @cache def count(c1, c2, M): return min(sum(count(cc1, cc2, M - 1) for cc1, cc2 in pairwise('A' + t + 'A')) for t in GCT[c1][c2]) if M > 0 else 1 ans = 0 for s0 in f: l = min(sum(count(cc1, cc2, 25) for cc1, cc2 in pairwise('A' + t + 'A')) for t in map(lambda l: 'A'.join(l), r(G0T, s0))) ans += l * int(s0[:-1]) print(ans) part2()
python