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 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | #! /usr/bin/env ruby
class RandomGenerator
def initialize(seed)
@seed = seed
end
def next
a = @seed * 64
mix(a)
prune!
b = @seed / 32
mix(b)
prune!
c = @seed * 2048
mix(c)
prune!
@seed
end
def mix(a)
@seed = @seed ^ a
end
def prune!
@seed = @seed % 16_777_216
end
end
#---------------------------------------------------------------------------------
input_file = "input.txt"
seeds = File.readlines(input_file).map(&:strip).reject(&:empty?).map(&:to_i)
sum_of_secrets = 0
seeds.each do |seed|
puts "Seed: #{seed}"
random_generator = RandomGenerator.new(seed)
1999.times { random_generator.next }
secret_number = random_generator.next
puts "#{seed}: 2000th random number: #{secret_number}"
sum_of_secrets += secret_number
end
puts "Sum of secrets: #{sum_of_secrets}" | ruby |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | #!/usr/bin/env ruby
# Login to https://adventofcode.com/2024/day/22/input to download 'input.txt'.
# lines = readlines
# lines = File.readlines('sample1.txt', chomp: true) # Answer: 37327623 (in 56 ms)
lines = File.readlines('input.txt', chomp: true) # Answer: 17612566393 (in 792 ms)
initial_numbers = lines.map(&:to_i)
puts 'Initial Numbers'
puts '---------------'
puts initial_numbers
puts
def next_secret_number(secret_number)
secret_number = mix_and_prune(secret_number, secret_number << 6) # Multiply by 64, or shift left by 6 bits
secret_number = mix_and_prune(secret_number, secret_number >> 5) # Divide by 32, or shift right by 5 bits
secret_number = mix_and_prune(secret_number, secret_number << 11) # Multiply by 2048, or shift left by 11 bits
end
def mix_and_prune(n, mixin)
# mix: XOR together
# prune: modulo 16777216 (keep the lowest 24 bits, or AND with 16777215 (all 1's))
(n ^ mixin) & 16777215
end
next_2000_secret_numbers = initial_numbers.map do |secret_number|
2000.times.reduce(secret_number) { |acc, _| next_secret_number(acc) }
end
puts '2000th Numbers'
puts '--------------'
puts next_2000_secret_numbers
puts
answer = next_2000_secret_numbers.sum
puts "Answer: #{answer}" | ruby |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | input_array = ARGV
def next_secret_number(secret_number)
secret_number = ((secret_number * 64) ^ secret_number) % 16777216
secret_number = ((secret_number / 32).floor ^ secret_number) % 16777216
secret_number = ((secret_number * 2048) ^ secret_number) % 16777216
end
def process(file_name, debug=false)
secret_numbers = []
File.foreach(ARGV[0]).with_index do |line, index|
row = line.strip.to_i
secret_numbers.push(row)
end
secret_total = 0
secret_numbers.each do |secret_number|
initial_secret_number = secret_number
2000.times do
secret_number = next_secret_number(secret_number)
end
puts "#{initial_secret_number}: #{secret_number}" if debug
secret_total += secret_number
end
puts "Secret total: #{secret_total}"
end
process(input_array[0], !input_array.at(1).nil?) | ruby |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | secret_sum = 0
num_iterations = 2000
mul_by_64_shift = 6
div_by_32_shift = 5
mul_by_2048_shift = 11
mod_val = 0x1000000 - 1
File.readlines("day_22_input.txt").each do |line|
n = line.strip.to_i
num_iterations.times do
n = (n ^ (n << mul_by_64_shift)) & mod_val # multiply by 64, XOR with original value, mod 16777216
n = (n ^ (n >> div_by_32_shift)) & mod_val # divide by 32, XOR with original value, mod 16777216
n = (n ^ (n << mul_by_2048_shift)) & mod_val # multiply by 2048, XOR with original value, mod 16777216
end
secret_sum += n
end
puts "Part 1 Answer: #{secret_sum}" | ruby |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | TEST = false
path = TEST ? 'example_input.txt' : 'input.txt'
PRUNE_MASK = 0b111111111111111111111111
codes = File.read(path).split("\n").map(&:to_i)
def next_code(code)
tmp = code << 6
code = code ^ tmp
code = code & PRUNE_MASK
tmp = code >> 5
code = code ^ tmp
code = code & PRUNE_MASK
tmp = code << 11
code = code ^ tmp
code & PRUNE_MASK
end
res = codes.map do |code|
2000.times do
code = next_code(code)
end
code
end
puts res.sum | ruby |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | #! /usr/bin/env ruby
class RandomGenerator
def initialize(seed)
@seed = seed
end
def next
mix_and_prune(@seed * 64)
mix_and_prune(@seed / 32)
mix_and_prune(@seed * 2048)
@seed
end
def mix_and_prune(a)
@seed = (@seed ^ a) % 16_777_216
end
end
#---------------------------------------------------------------------------------
input_file = ENV['REAL'] ? "input.txt" : "input-demo2.txt"
seeds = File.readlines(input_file).map(&:strip).reject(&:empty?).map(&:to_i)
shared_ngrams = Hash.new(0)
seeds.each do |seed|
random_generator = RandomGenerator.new(seed)
previous_price = seed % 10
price_diff_pairs = []
2000.times do
price = random_generator.next % 10
diff = price - previous_price
previous_price = price
price_diff_pairs << { price: , diff: }
end
# generate all price n-grams of length 4 and record each n-gram with the price at the end of the n-gram
seen_ngrams = Set.new
price_diff_pairs.each_cons(4) do |window|
price = window.last[:price]
ngram = window.map { |p| p[:diff] }
next unless seen_ngrams.add?(ngram)
shared_ngrams[ngram] += price
end
end
ngram, price = shared_ngrams.max_by { |ngram, price| price }
puts "Best ngram: #{ngram.join(',')} -> #{price}" | ruby |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | TEST = false
path = TEST ? 'example_input.txt' : 'input.txt'
PRUNE_MASK = 0b111111111111111111111111
PRUNE_MODULO = 16777216
codes = File.read(path).split("\n").map(&:to_i)
def next_code(code)
tmp = code << 6
code = code ^ tmp
code = code & PRUNE_MASK
tmp = code >> 5
code = code ^ tmp
code = code & PRUNE_MASK
tmp = code << 11
code = code ^ tmp
code & PRUNE_MASK
end
def compute_codes(code, times)
codes = Array.new(times)
codes[0] = code
(1...codes.count).each do |i|
previous_code = i.zero? ? code : codes[i - 1]
codes[i] = next_code(previous_code)
end
codes
end
def compute_price_diffs(codes)
prices = codes.map { _1 % 10 }
diffs = prices.map.with_index { |price, i| i.zero? ? nil : price - prices[i - 1] }
[prices, diffs]
end
def compute_sequences(prices, diffs)
sequences = Hash.new
(4...prices.count).each do |i|
key = "#{diffs[i-3]}#{diffs[i-2]}#{diffs[i-1]}#{diffs[i]}"
sequences[key] = prices[i] unless sequences.key?(key)
end
sequences
end
puts "Computing sequences..."
sequences = codes.map do |code|
new_codes = compute_codes(code, 2001)
prices, diffs = compute_price_diffs(new_codes)
compute_sequences(prices, diffs)
end
puts "Sequences computed"
all_keys = sequences.flat_map(&:keys).uniq
puts "#{all_keys.count} keys to try..."
values = all_keys.map do |key|
sequences.reduce(0) do |sum, sequences_hash|
sequences_hash.key?(key) ? sum + sequences_hash[key] : sum
end
end
puts "Done"
puts values.max | ruby |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | input_array = ARGV
def next_secret_number(secret_number)
secret_number = ((secret_number * 64) ^ secret_number) % 16777216
secret_number = ((secret_number / 32).floor ^ secret_number) % 16777216
secret_number = ((secret_number * 2048) ^ secret_number) % 16777216
end
def process(file_name, debug=false)
secret_numbers = []
File.foreach(ARGV[0]).with_index do |line, index|
row = line.strip.to_i
secret_numbers.push(row)
end
secret_total = 0
sequences = []
secret_numbers.each do |secret_number|
initial_secret_number = secret_number
sequence_to_price = {}
sequence = []
previous_price = nil
2000.times do
bananas = secret_number % 10
sequence.push(bananas - previous_price) if !previous_price.nil?
previous_price = bananas
if sequence.length == 4
sequence_to_price[sequence.join(",")] = bananas if sequence_to_price[sequence.join(",")].nil?
sequence.shift
end
secret_number = next_secret_number(secret_number)
end
sequences.push(sequence_to_price)
puts "#{initial_secret_number}: #{secret_number}" if debug
puts "Sequences:\n#{sequences}" if debug
secret_total += secret_number
end
max_sequence = nil
max_sequence_amount = 0
all_sequences = sequences.map { |s| s.keys }.flatten.uniq
all_sequences.each do |sequence|
sequence_amount = sequences.map { |s| s[sequence] }.compact.sum
if sequence_amount > max_sequence_amount
max_sequence = sequence
max_sequence_amount = sequence_amount
end
end
puts "Max sequence: #{max_sequence}, bananas: #{max_sequence_amount}"
puts "Secret total: #{secret_total}"
end
process(input_array[0], !input_array.at(1).nil?) | ruby |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | #!/usr/bin/env ruby
# frozen_string_literal: true
file_path = File.expand_path('input.txt', __dir__)
$cache_1 = {}
def generate_secret_number(secret_number)
return $cache_1[secret_number] if $cache_1.has_key?(secret_number)
start = secret_number
result = secret_number * 64
secret_number ^= result
secret_number %= 16777216
result = secret_number / 32
secret_number ^= result
secret_number %= 16777216
result = secret_number * 2048
secret_number ^= result
secret_number %= 16777216
$cache_1[start] = secret_number
return secret_number
end
$sequences = {}
def generate_nth_secret_number(secret_number, n)
start = secret_number
prev_price = secret_number % 10
prices = [prev_price]
diffs = []
customer_sequences = {}
n.times do |i|
secret_number = generate_secret_number(secret_number)
price = secret_number % 10
diff = price - prev_price
prev_price = price
diffs << diff
prices << price
if i > 3
seq = diffs[i-3..i].join(',')
next if customer_sequences.has_key?(seq)
customer_sequences[seq] = prices[i+1]
end
end
customer_sequences.each do |seq, price|
$sequences[seq] ||= []
$sequences[seq] << price
end
return secret_number
end
input = File.read(file_path).split("\n").map(&:to_i)
sum = 0
input.each do |secret_number|
sum += generate_nth_secret_number(secret_number, 2000)
end
puts $sequences.map { |seq, prices| prices.sum }.max | ruby |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | #!/usr/bin/env ruby
# Login to https://adventofcode.com/2024/day/22/input to download 'input.txt'.
# lines = readlines
# lines = File.readlines('sample2.txt', chomp: true) # Answer: 23 (in 73 ms)
lines = File.readlines('input.txt', chomp: true) # Answer: 1968 (in 21,706 ms)
initial_numbers = lines.map(&:to_i)
puts 'Initial Numbers'
puts '---------------'
puts initial_numbers
puts
def next_secret_number(secret_number)
secret_number = mix_and_prune(secret_number, secret_number << 6) # Multiply by 64, or shift left by 6 bits
secret_number = mix_and_prune(secret_number, secret_number >> 5) # Divide by 32, or shift right by 5 bits
secret_number = mix_and_prune(secret_number, secret_number << 11) # Multiply by 2048, or shift left by 11 bits
end
def mix_and_prune(n, mixin)
# mix: XOR together
# prune: modulo 16777216 (keep the lowest 24 bits, or AND with 16777215 (all 1's))
(n ^ mixin) & 16777215
end
def price(secret_number)
secret_number % 10
end
sequences = initial_numbers.map do |n|
first_frame = { secret_number: n, price: price(n), delta: nil }
2000.times.reduce([first_frame]) do |acc, _|
previous = acc.last
secret_number = next_secret_number(previous[:secret_number])
price = price(secret_number)
acc << {
secret_number:,
price:,
delta: price - previous[:price],
}
end
end
puts 'Sequences'
puts '---------'
sequences.each do |sequence|
puts sequence.take(10)
puts '...'
puts
end
pattern_sets = sequences.map do |sequence|
pattern = []
sequence.reduce(Hash.new(0)) do |hash, frame|
pattern << frame[:delta] unless frame[:delta].nil?
pattern.shift if pattern.size > 4
if pattern.size == 4
key = pattern.join(',')
hash[key] = frame[:price] unless hash.key?(key)
end
hash
end
end
puts 'Pattern Sets'
puts '------------'
pattern_sets.each do |patterns|
patterns.take(10).each do |pattern, price|
puts "#{pattern}: #{price}"
end
puts '...'
puts
end
patterns = pattern_sets.map(&:keys).flatten.uniq
puts 'Patterns'
puts '--------'
puts patterns.take(10)
puts '...'
puts
patterns_and_prices = patterns.reduce({}) do |hash, pattern|
hash[pattern] = pattern_sets.map { |set| set[pattern] }
hash
end
puts 'Patterns w/ Prices'
puts '------------------'
puts patterns_and_prices.take(10).to_h
puts '...'
puts
answer = patterns_and_prices.map { |_, prices| prices.sum }.max
puts "Answer: #{answer}" | ruby |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | class Day23
def initialize()
@network = Hash.new
end
def read_process_input
File.open(""Day23\\input23".txt", "r") do |f|
f.each_line.with_index do |line, i|
computers = line.gsub("\n","").split("-")
if !@network.key?(computers[0])
@network[computers[0]] = []
end
if !@network.key?(computers[1])
@network[computers[1]] = []
end
@network[computers[0]].push(computers[1])
@network[computers[1]].push(computers[0])
end
end
end
def find_groups
relevant_grops = Set.new
visited = []
for key in @network.keys
if !visited.include?(key)
other_computers = @network[key]
visited.push(key)
if other_computers.length >= 2
for i in 0..other_computers.length-1
other_computer_network = @network[other_computers[i]]
common_computers = other_computers & other_computer_network
if common_computers.length > 0
for j in 0..common_computers.length-1
last_computer_network = @network[common_computers[j]]
if last_computer_network.include?(key) &&
last_computer_network.include?(other_computers[i])
if key.start_with?("t") || common_computers[j].start_with?("t") ||
other_computers[i].start_with?("t")
relevant_grops.add([key, other_computers[i], common_computers[j]].sort)
end
end
end
end
end
end
end
end
return relevant_grops.length
end
end
day23 = Day23.new()
day23.read_process_input
puts day23.find_groups | ruby |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | #!/usr/bin/env ruby
# frozen_string_literal: true
file_path = File.expand_path('input.txt', __dir__)
input = File.read(file_path).split("\n").map{ |line| line.split('-') }
temp_groups = []
groups = []
(input.size).times do |i|
x1 = input[i][0]
x2 = input[i][1]
(input.size).times do |j|
next if i == j
y1 = input[j][0]
y2 = input[j][1]
if (x1 == x2 || x1 == y2 || y1 == x2 || y1 == y2)
temp_groups << [input[i], input[j]]
end
end
end
temp_groups = temp_groups.map { |group| group.sort }
temp_groups.each do |group|
(input.size).times do |i|
x1 = input[i][0]
x2 = input[i][1]
non_overlapping = group.flatten(1).tally.select { |k, v| v == 1 }.keys
c1 = non_overlapping[0]
c2 = non_overlapping[1]
if (x1 == c1 && x2 == c2) || (x1 == c2 && x2 == c1)
new_group = group.concat([input[i]])
groups << new_group
end
end
end
groups = groups.map { |group| group.flatten.uniq.sort }.uniq
puts groups.select { |group| group.any? { |comp| comp[0] == "t"} }.size | ruby |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | # As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
# The network map provides a list of every connection between two computers. For example:
# kh-tc
# qp-kh
# de-cg
# ka-co
# yn-aq
# qp-ub
# cg-tb
# vc-aq
# tb-ka
# wh-tc
# yn-cg
# kh-ub
# ta-co
# de-co
# tc-td
# tb-wq
# wh-td
# ta-ka
# td-qp
# aq-cg
# wq-ub
# ub-vc
# de-ta
# wq-aq
# wq-vc
# wh-yn
# ka-de
# kh-ta
# co-tc
# wh-qp
# tb-vc
# td-yn
# Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
# LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
# In this example, there are 12 such sets of three inter-connected computers:
# aq,cg,yn
# aq,vc,wq
# co,de,ka
# co,de,ta
# co,ka,ta
# de,ka,ta
# kh,qp,ub
# qp,td,wh
# tb,vc,wq
# tc,td,wh
# td,wh,yn
# ub,vc,wq
# If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
# co,de,ta
# co,ka,ta
# de,ka,ta
# qp,td,wh
# tb,vc,wq
# tc,td,wh
# td,wh,yn
# Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
input_array = ARGV
def find_three_connected_computers(adjacency_list)
three_connected_computers = []
adjacency_list.each do |computer, connections|
next if !computer.start_with?('t') && !connections.any? {|connection| connection.start_with?('t')}
connections.each do |connection|
adjacency_list[connection].each do |connection2|
if connections.include?(connection2)
connected_computers = [computer, connection, connection2].sort
three_connected_computers.push(connected_computers) unless three_connected_computers.include?(connected_computers)
end
end
end
end
three_connected_computers
end
def process(file_name, debug=false)
adjacency_list = {}
File.foreach(ARGV[0]).with_index do |line, index|
row = line.strip.split('-')
node1 = row[0]
node2 = row[1]
adjacency_list[node1] = [] if adjacency_list[node1].nil?
adjacency_list[node1].push(node2)
adjacency_list[node2] = [] if adjacency_list[node2].nil?
adjacency_list[node2].push(node1)
end
puts "Adjacency list: #{adjacency_list}" if debug
three_connected_computers = find_three_connected_computers(adjacency_list)
puts "Three connected computers: #{three_connected_computers}" if debug
t_networks = three_connected_computers.select {|network| network.any? {|computer| computer.start_with?('t')}}
puts "Three connected computers count with 't': #{t_networks.length}"
end
process(input_array[0], !input_array.at(1).nil?) | ruby |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | require 'set'
input = File.readlines('day-23/input.txt').map(&:chomp)
computers = Hash.new { |h, k| h[k] = Set.new }
input.each do |line|
computer_names = line.split('-')
computers[computer_names[0]].add(computer_names[1])
computers[computer_names[1]].add(computer_names[0])
end
triangles = Set[]
computers.each do |computer, connected_computers|
connected_computers.to_a.combination(2).each do |combination|
triangles.add(Set[computer, combination[0], combination[1]]) if computers[combination[0]].include?(combination[1])
end
end
pp triangles.select { |triangle| triangle.any? { |computer| computer[0] == 't'} }.size | ruby |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | #!/usr/bin/env ruby
# Login to https://adventofcode.com/2024/day/23/input to download 'input.txt'.
# lines = readlines
# lines = File.readlines('sample.txt', chomp: true) # Answer: 7 (in 54 ms)
lines = File.readlines('input.txt', chomp: true) # Answer: 1423 (in 60 ms)
network = lines
.map { |line| line.split('-') }
.reduce(Hash.new { |hash, key| hash[key] = [] }) { |hash, pair| hash[pair[0]] << pair[1]; hash[pair[1]] << pair[0]; hash }
puts "Network (#{network.size})"
puts '-------'
network.sort.select { |computer, _| computer.start_with?('t') }.each do |computer, connections|
puts "#{computer} is connected to #{connections.sort} (#{connections.size})"
end
puts
triplets = network
.select { |computer, _| computer.start_with?('t') }
.collect do |computer, connections|
connections.collect do |connection|
connections
.intersection(network[connection])
.collect { |third| [computer, connection, third] }
.map(&:sort)
.map { |triplet| triplet.join(',') }
end
end
.flatten
.uniq
puts "Triplets (#{triplets.size})"
puts '-------'
puts triplets.sort
puts
answer = triplets.size
puts "Answer: #{answer}" | ruby |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | #!/usr/bin/env ruby
# Login to https://adventofcode.com/2024/day/23/input to download 'input.txt'.
# lines = readlines
# lines = File.readlines('sample.txt', chomp: true) # Answer: co,de,ka,ta (in 61 ms)
lines = File.readlines('input.txt', chomp: true) # Answer: gt,ha,ir,jn,jq,kb,lr,lt,nl,oj,pp,qh,vy (in 74 ms)
network = lines
.map { |line| line.split('-') }
.reduce(Hash.new { |hash, key| hash[key] = [] }) { |hash, pair| hash[pair[0]] << pair[1]; hash[pair[1]] << pair[0]; hash }
puts "Network (#{network.select { |computer, _| computer.start_with?('t') }.size} / #{network.size})"
puts '-------'
network.sort.select { |computer, _| computer.start_with?('t') }.each do |computer, connections|
puts "#{computer} is connected to #{connections.sort} (#{connections.size})"
end
puts
def cannon(c1, c2)
c1 < c2 ? "#{c1}-#{c2}" : "#{c2}-#{c1}"
end
cannonical_connections = lines
.map { |line| line.split('-') }
.map { |c1, c2| cannon(c1, c2) }
.to_set
puts "Cannonical Connections (#{cannonical_connections.size})"
puts '----------------------'
puts '...'
puts
lan_parties = network
# .select { |computer, _| computer.start_with?('t') } # Assumption: the largest LAN party will include a computer starting with 't'
.collect do |computer, connections|
lan_party = [computer]
connections.each do |c1|
if lan_party.all? { |c2| cannonical_connections.include?(cannon(c1, c2)) }
lan_party << c1
end
end
lan_party
end
sorted_lan_parties = lan_parties
.map(&:sort)
.map { |lan_party| lan_party.join(',') }
.uniq
.sort_by(&:size)
puts
puts "LAN Parties (#{lan_parties.size})"
puts '-----------'
puts sorted_lan_parties.take(5)
puts '...'
puts sorted_lan_parties.reverse.take(5).reverse
puts
puts "Answer: #{sorted_lan_parties.last}" | ruby |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | TEST = false
path = TEST ? 'example_input.txt' : 'input.txt'
connections = File.read(path).split("\n").map { _1.split('-') }
class Computer
attr_accessor :name
attr_accessor :connected_computers
def initialize(name)
@name = name
@connected_computers = Set.new
end
def ==(other)
other.is_a? Computer and @name == other.name
end
def eql?(other)
other.is_a? Computer and @name.eql? other.name
end
def hash
@name.hash
end
def connect_to(computer)
@connected_computers << computer
end
def to_s
"Computer #{@name}; connected to #{@connected_computers.map(&:name).join(', ')}."
end
def connected_groups(res_set, verified = Set[], unverified = connected_computers + Set[self])
new_verified = verified + Set[self]
new_unverified = unverified & connected_computers
if new_unverified.empty?
res_set << new_verified
return
end
new_unverified.each { |comp| comp.connected_groups(res_set, new_verified, new_unverified) }
end
def self.connect(comp1, comp2)
comp1.connect_to(comp2)
comp2.connect_to(comp1)
end
def self.password_by_building_sets(sets, computers)
puts "#{sets.count} sets of #{sets.first.count}"
return sets.first.map(&:name).sort.join(',') if sets.count == 1
return 'FUCK' if sets.empty?
bigger_sets = Set[]
sets.each do |set|
computers.each do |computer|
bigger_sets << set + Set[computer] if set.subset?(computer.connected_computers)
end
end
password_by_building_sets(bigger_sets, computers)
end
end
def build(connections)
computers = Hash.new
connections.each do |connection|
name1 = connection[0]
comp1 = computers[name1] || Computer.new(name1)
computers[name1] = comp1
name2 = connection[1]
comp2 = computers[name2] || Computer.new(name2)
computers[name2] = comp2
Computer.connect(comp1, comp2)
end
computers.values
end
def sets_of_three(computers)
sets = Set.new
computers.each do |computer|
computer.connected_computers.each do |comp2|
comp2.connected_computers.each do |comp3|
sets << Set[computer, comp2, comp3] if comp3.connected_computers.include?(computer)
end
end
end
sets
end
computers = build(connections)
sets = sets_of_three(computers)
p "Password: #{Computer.password_by_building_sets(sets, computers)}" | ruby |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | # There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
# Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
# In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
# ka-co
# ta-co
# de-co
# ta-ka
# de-ta
# ka-de
# The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
# What is the password to get into the LAN party?
input_array = ARGV
def find_largest_lan_party(adjacency_list)
largest_lan_party = []
adjacency_list.each do |computer, connections|
lan_party = [computer]
connections.each do |connection|
all_connected = lan_party.all? { |lan_party_computer| adjacency_list[connection].include?(lan_party_computer) }
lan_party.push(connection) if all_connected
end
largest_lan_party = lan_party if lan_party.length > largest_lan_party.length
end
puts "Largest LAN party: #{largest_lan_party}"
password = largest_lan_party.sort.join(',')
puts "Password: #{password}"
end
def process(file_name, debug=false)
adjacency_list = {}
File.foreach(ARGV[0]).with_index do |line, index|
row = line.strip.split('-')
node1 = row[0]
node2 = row[1]
adjacency_list[node1] = [] if adjacency_list[node1].nil?
adjacency_list[node1].push(node2)
adjacency_list[node2] = [] if adjacency_list[node2].nil?
adjacency_list[node2].push(node1)
end
puts "Adjacency list: #{adjacency_list}" if debug
find_largest_lan_party(adjacency_list)
end
process(input_array[0], !input_array.at(1).nil?) | ruby |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | #! /usr/bin/env ruby
class CliqueFinder
attr_reader :maximal_clique, :network
def initialize(network)
@network = network
@maximal_clique = Set.new
end
def bron_kerbosch(current: Set.new, candidates:, excluded: Set.new)
if candidates.empty? && excluded.empty?
@maximal_clique = current.to_a.sort if current.size > maximal_clique.size
return @maximal_clique
end
pivot = candidates.first # Pick a pivot node (makes it a lot faster)
non_neighbors = candidates - network[pivot]
non_neighbors.each do |v|
current.add(v)
next_p = candidates & network[v]
next_x = excluded & network[v]
bron_kerbosch(current: current, candidates: next_p, excluded: next_x)
current.delete(v)
excluded.add(v)
end
maximal_clique
end
end
network = Hash.new { |h, k| h[k] = Set.new }
input_file = ENV['REAL'] ? "input.txt" : "input-demo.txt"
lines = File.readlines(input_file).map(&:strip).reject(&:empty?)
lines.each do |line|
from, to = line.split('-')
network[from].add(to)
network[to].add(from)
end
clique_finder = CliqueFinder.new(network)
result = clique_finder.bron_kerbosch(candidates: Set.new(network.keys))
puts "result: #{result.join(',')}"
# am,au,be,cm,fo,ha,hh,im,nt,os,qz,rr,so - good
| ruby |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | #!/usr/bin/env ruby
# frozen_string_literal: true
require 'set'
largest_cluster = []
def expand_nodes(r, p, x, graph, largest_cluster)
if p.empty? && x.empty?
largest_cluster.replace(r) if r.size > largest_cluster.size
return
end
pivot = (p + x).first
(p - graph[pivot]).each do |v|
expand_nodes(
r + [v],
p & graph[v],
x & graph[v],
graph,
largest_cluster
)
p.delete(v)
x.add(v)
end
end
file_path = File.expand_path('input.txt', __dir__)
groups = File.read(file_path).split("\n").map{ |line| line.split('-') }
connections = {}
groups.each do |group|
connections[group[0]] ||= []
connections[group[0]] << group[1]
connections[group[1]] ||= []
connections[group[1]] << group[0]
end
graph = connections.transform_values { |neighbors| neighbors.to_set }
nodes = graph.keys.sort_by { |node| graph[node].size }
expand_nodes([], nodes.to_set, Set.new, graph, largest_cluster)
puts largest_cluster.sort.join(',') | ruby |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | GateInput = Struct.new(:a, :b, :out, :operator)
class Gates
def initialize(filename)
@outputs = Hash.new
inputs = []
File.readlines(filename).each do |line|
if line.include?(":")
match = line.match(/([\w\d]+):\s*(1|0)/)
@outputs[match[1]] = match[2].to_i
elsif line.include?("->")
match = line.match(/([\w\d]+)\s*([\w\d]+)\s*([\w\d]+)\s*->\s*([\w\d]+)/)
inputs.append(GateInput.new(match[1], match[3], match[4], match[2]))
end
end
# Convert inputs into outputs
while !inputs.empty? do
input_to_convert_index = -1
inputs.each_with_index do |input, index|
if !@outputs.key?(input.a) || !@outputs.key?(input.b)
next
end
input_to_convert_index = index
break
end
if input_to_convert_index == -1
puts "Error: Couldn't find input to convert!"
break
end
input = inputs[input_to_convert_index]
case input.operator
when "AND"
@outputs[input.out] = (@outputs[input.a] == 1) && (@outputs[input.b] == 1) ? 1 : 0
when "OR"
@outputs[input.out] = (@outputs[input.a] == 1) || (@outputs[input.b] == 1) ? 1 : 0
when "XOR"
@outputs[input.out] = (@outputs[input.a] != @outputs[input.b]) ? 1 : 0
end
inputs.delete_at(input_to_convert_index)
end
#p @outputs.to_a.sort
end
def solve_part_1
final_output = 0
@outputs.each do |k, v|
if k[0] != "z" || v == 0
next
end
bit_place = k.delete("z").to_i
final_output |= (1 << bit_place)
end
puts "Part 1 Answer: #{final_output}"
end
end
gates = Gates.new("day_24_input.txt")
gates.solve_part_1 | ruby |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | require 'set'
class Gate
attr_accessor :input_wires, :operation, :output_wire
def initialize(input_wires, operation, output_wire, wires)
@input_wires = input_wires
@operation = operation
@output_wire = output_wire
@wires = wires
end
def execute!
return unless @wires[@output_wire].nil?
return if @wires[@input_wires[0]].nil?
return if @wires[@input_wires[1]].nil?
if @operation == 'AND'
@wires[output_wire] = @wires[@input_wires[0]] & @wires[@input_wires[1]]
elsif @operation == 'OR'
@wires[output_wire] = @wires[@input_wires[0]] | @wires[@input_wires[1]]
else # XOR
@wires[output_wire] = @wires[@input_wires[0]] ^ @wires[@input_wires[1]]
end
end
end
def execute(gates)
while @wires.select { |key, _| key[0] == 'z' }.any? { |_, value| value.nil? }
gates.each(&:execute!)
end
result = 0
@wires.keys.select { |key| key[0] == 'z' }.sort.reverse_each do |key|
result <<= 1
result += @wires[key]
end
result
end
lines = File.readlines('day-24/input.txt').map(&:chomp)
@wires = Hash.new(nil)
gates = Set[]
lines.reverse_each do |line|
if line.include?('->')
split_line = line.split(' ')
@wires[split_line[0]] = nil
@wires[split_line[2]] = nil
@wires[split_line[4]] = nil
gates.add(Gate.new([split_line[0], split_line[2]], split_line[1], split_line[4], @wires))
elsif line.include?(':')
split_line = line.split(': ')
@wires[split_line[0]] = split_line[1].to_i
end
end
pp execute(gates) | ruby |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | class Day24
def initialize()
@inputs = Hash.new
@operators_queue = [] # (var, op, var, output)
end
def read_process_input
File.open("Day24\\input24.txt", "r") do |f|
f.each_line.with_index do |line, i|
if line.include?(":")
line = line.split(":")
@inputs[line[0]] = line[1].strip.to_i
elsif !line.strip.empty?
if line.include?("AND")
op = line.split("AND")
tmp = op[1].split("->")
@operators_queue.push([op[0].strip, "AND", tmp[0].strip, tmp[1].strip])
elsif line.include?("XOR")
op = line.split("XOR")
tmp = op[1].split("->")
@operators_queue.push([op[0].strip, "XOR", tmp[0].strip, tmp[1].strip])
elsif line.include?("OR")
op = line.split("OR")
tmp = op[1].split("->")
@operators_queue.push([op[0].strip, "OR", tmp[0].strip, tmp[1].strip])
end
end
end
end
end
def calculate
@operators_queue.each { |op_combination|
var1 = op_combination[0]
op = op_combination[1]
var2 = op_combination[2]
output = op_combination[3]
if @inputs.key?(var1) && @inputs.key?(var2)
if op == "AND"
@inputs[output] = @inputs[var1] & @inputs[var2]
elsif op == "OR"
@inputs[output] = @inputs[var1] | @inputs[var2]
elsif op == "XOR"
@inputs[output] = @inputs[var1] ^ @inputs[var2]
end
else
@operators_queue.push([var1, op, var2, output])
end
}
first_output = @inputs["z00"]
incr = 0
res = ""
while first_output != nil
res += first_output.to_s
incr += 1
incr_string = incr.to_s
if incr_string.size == 1
incr_string = "0" + incr_string
end
incr_string = "z" + incr_string
first_output = @inputs[incr_string]
end
return res.reverse!.to_i(2)
end
end
day24 = Day24.new()
day24.read_process_input
puts day24.calculate | ruby |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | #!/usr/bin/env ruby
# frozen_string_literal: true
file_path = File.expand_path('input.txt', __dir__)
input = File.read(file_path).split("\n\n")
inputs = input[0].split("\n").map do |line|
l = line.split(': ')
[l[0], l[1].to_i]
end.to_h
gates = input[1].split("\n").map do |line|
l = line.scan(/(\w+) (\w+) (\w+) -> (\w+)/).flatten
{
gate1: l[0],
gate2: l[2],
operation: l[1],
output: l[3]
}
end
while gates.size > 0 do
gates.each_with_index do |gate, index|
if inputs.has_key?(gate[:gate1]) && inputs.has_key?(gate[:gate2])
if gate[:operation] == 'AND'
inputs[gate[:output]] = inputs[gate[:gate1]] & inputs[gate[:gate2]]
gates.delete_at(index)
elsif gate[:operation] == 'OR'
inputs[gate[:output]] = inputs[gate[:gate1]] | inputs[gate[:gate2]]
gates.delete_at(index)
else
inputs[gate[:output]] = inputs[gate[:gate1]] ^ inputs[gate[:gate2]]
gates.delete_at(index)
end
end
end
end
puts inputs.select { |k, v| k[0] == 'z' }.sort.reverse.map { |k, v| v.to_s }.join.to_i(2).to_s(10) | ruby |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | #! /usr/bin/env ruby
def calculate(wires, wire)
return wires[wire] unless wires[wire].is_a?(Hash)
a, op, b = wires[wire].values_at(:a, :op, :b)
a = calculate(wires, a)
b = calculate(wires, b)
wires[wire] = case op
when "AND"
a & b
when "OR"
a | b
when "XOR"
a ^ b
end
wires[wire]
end
input_file = ENV['REAL'] ? "input.txt" : "input-demo.txt"
lines = File.readlines(input_file)
wires = {}
while line = lines.shift
break if line.strip.empty?
name, value = line.strip.split(":").map(&:strip)
wires[name] = value.to_i == 1
end
while line = lines.shift
eq, output = line.strip.split("->").map(&:strip)
a, op, b = eq.split(" ")
wires[output] = { a:, op: , b: }
end
z_wires = wires.keys.select { |k| k.start_with?("z") }
z_bits = ''
z_wires.sort.each do |wire|
bit = calculate(wires, wire) ? 1 : 0
z_bits << bit.to_s
end
z_bits = z_bits.reverse.to_i(2)
puts z_bits.inspect | ruby |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | require 'set'
def test_input_1
_input = """x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02""".strip.split("\n")
raise unless part_1(_input) == 4
end
def test_input_2
_input = """x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj""".strip.split("\n")
raise unless part_1(_input) == 2024
end
def read_input(path)
File.readlines(path).map(&:strip)
end
def get_variables_and_gates(input_data)
variables = {}
gates = []
input_data.each do |line|
if line.include?(':')
variable, value = line.split(': ')
variables[variable] = value.to_i
elsif line.include?('->')
a, op, b, _, c = line.split
gates << [a, op, b, c]
end
end
[variables, gates]
end
def try_solve(variables, gate)
a, op, b, c = gate
av = variables[a]
bv = variables[b]
return false if av.nil? || bv.nil?
case op
when 'AND'
variables[c] = av & bv
when 'OR'
variables[c] = av | bv
when 'XOR'
variables[c] = av ^ bv
end
true
end
class Graph
def initialize
@nodes = {}
end
def add_node(node)
@nodes[node] ||= {}
end
def add_edge(node1, node2, description = "")
add_node(node1)
add_node(node2)
@nodes[node1][node2] = description
@nodes[node2][node1] = description
end
def nodes
@nodes
end
end
def part_1(input_data)
variables, gates = get_variables_and_gates(input_data)
queue = gates.dup
until queue.empty?
gate = queue.shift
unless try_solve(variables, gate)
queue.push(gate)
end
end
variables.keys.select { |key| key.start_with?('z') }
.sort
.map { |key| variables[key].to_s }
.join
.to_i(2)
end
def part_2(input_data)
_, gates = get_variables_and_gates(input_data)
g = Graph.new
gates.each do |gate|
a, op, b, c = gate
g.add_edge(c, a, op)
g.add_edge(c, b, op)
end
swaps = Set.new
(1..44).each do |i|
x = format("x%02d", i)
y = format("y%02d", i)
z = format("z%02d", i)
xors = g.nodes[x].key('XOR')
next unless xors
next_xor = g.nodes[xors].select { |k, v| v == 'XOR' }.keys
unless next_xor.include?(z)
if next_xor.size == 3
next_xor.each do |n|
if n != x && n != y
swaps.add(z)
swaps.add(n)
break
end
end
else
swaps.add(g.nodes[x].keys[0])
swaps.add(g.nodes[x].keys[1])
end
end
end
swaps.to_a.sort.join(',')
end
def main
input_data = read_input(ARGV[0])
puts "Part 1: #{part_1(input_data)}"
puts "Part 2: #{part_2(input_data)}"
end
if __FILE__ == $0
main
end | ruby |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | def parse_values(input)
value_hash = {}
input.split("\n\n")[0].lines.each do |ln|
key, val = ln.strip.split(':')
value_hash[key] = val.to_i
end
value_hash
end
def parse_gates(input)
gate_hash = {}
input.split("\n\n")[1].lines.each do |ln|
gate, res = ln.strip.split(' -> ')
if gate.include?(' AND ')
opr1, opr2 = gate.split(' AND ')
op = 'AND'
elsif gate.include?(' XOR ')
opr1, opr2 = gate.split(' XOR ')
op = 'XOR'
elsif gate.include?(' OR ')
opr1, opr2 = gate.split(' OR ')
op = 'OR'
end
gate_hash[res] = [opr1, op, opr2]
end
gate_hash
end
def parse_input(file)
input = File.read(File.join(File.dirname(__FILE__), file))
values = parse_values(input)
gate_hash = parse_gates(input)
dependencies = build_dependencies(values, gate_hash)
operations = sort_operations(gate_hash, dependencies)
[values, operations]
end
def build_dependencies(value_hash, gate_hash)
dependencies = {}
gate_hash.each do |gate, ops|
dependencies[gate] = []
dependencies[gate].append(ops[0]) if !value_hash.keys.include?(ops[0]) && gate_hash.keys.include?(ops[0])
dependencies[gate].append(ops[2]) if !value_hash.keys.include?(ops[2]) && gate_hash.keys.include?(ops[2])
end
dependencies
end
def sort_operations(gate_hash, dependencies)
in_degree = {}
dependencies.each { |val, deps| in_degree[val] = deps.length }
queue = in_degree.select { |_k, v| v.zero? }.keys
sorted_operations = []
until queue.empty?
current = queue.shift
sorted_operations.append([current, gate_hash[current]].flatten)
gate_hash.each do |res, ops|
if ops[0] == current || ops[2] == current
in_degree[res] -= 1
queue.append(res) if (in_degree[res]).zero?
end
end
end
sorted_operations
end
def gate_operation(opr1, op, opr2)
case op
when 'AND' then opr1 & opr2
when 'XOR' then opr1 ^ opr2
when 'OR' then opr1 | opr2
end
end
def crossed_wires(file)
values, operations = parse_input(file)
operations.each do |op|
result, opr1, op, opr2 = op
values[result] = gate_operation(values[opr1], op, values[opr2])
end
values.select { |k, _v| k.chars.first == 'z' }.sort.reverse.map { |z| z[1] }.join.to_i(2)
end
def operation_valid?(op, operations)
result, opr1, op, opr2 = op
return false if result.chars.first == 'z' && op != 'XOR' && !result.include?('45')
if result.chars.first != 'z' && op == 'XOR'
return false if [opr1, opr2].none? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') }
end
if [opr1, opr2].all? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') } && op == 'XOR'
if [opr1, opr2].none? { |o| o.include?('00') }
return false if operations.none? { |op| op[1..].include?(result) && op[2] == 'XOR' }
end
end
if [opr1, opr2].all? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') } && op == 'AND'
if [opr1, opr2].none? { |o| o.include?('00') }
return false if operations.none? { |op| op[1..].include?(result) && op[2] == 'OR' }
end
end
true
end
def faulty_wires(file)
_, operations = parse_input(file)
faulty = []
operations.each do |op|
faulty.append(op) unless operation_valid?(op, operations)
end
faulty.map(&:first).sort.join(',')
end
input_file = 'day24-input.txt'
# Part 1
puts crossed_wires(input_file)
# Part 2
puts faulty_wires(input_file) | ruby |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | require 'set'
def parse_input(file)
wire_values = {}
gates = []
File.readlines(file).each do |line|
if line.include?("->")
expr, wire = line.strip.split(" -> ")
left, operator, right = expr.split(" ")
gates << { left: left, operator: operator, right: right, result: wire }
wire_values[wire] = nil # Initialize result wire with nil
elsif line.include?(":")
wire, value = line.strip.split(": ")
wire_values[wire] = value.to_i
end
end
[wire_values, gates]
end
def is_input?(operand)
operand.start_with?('x', 'y')
end
def build_usage_map(gates)
# Create a usage map of gates for operands
usage_map = Hash.new { |hash, key| hash[key] = [] }
gates.each do |gate|
usage_map[gate[:left]] << gate
usage_map[gate[:right]] << gate
end
usage_map
end
def xor_conditions_met?(left, right, result, usage_map)
if is_input?(left)
return true if !is_input?(right) || (result[0] == 'z' && result != 'z00')
used_ops = usage_map[result].map { |gate| gate[:operator] }
return result != 'z00' && used_ops.sort != ['AND', 'XOR']
elsif result[0] != 'z'
return true
end
false
end
def and_conditions_met?(left, right, result, usage_map)
if is_input?(left) && !is_input?(right)
return true
end
used_ops = usage_map[result].map { |gate| gate[:operator] }
used_ops != ['OR']
end
def or_conditions_met?(left, right, result, usage_map)
if is_input?(left) || is_input?(right)
return true
end
used_ops = usage_map[result].map { |gate| gate[:operator] }
used_ops.sort != ['AND', 'XOR']
end
def identify_swapped_wires(wire_values, gates)
usage_map = build_usage_map(gates)
swapped_wires = Set.new
gates.each do |gate|
left, op, right, result = gate[:left], gate[:operator], gate[:right], gate[:result]
next if result == 'z45' || left == 'x00'
case op
when 'XOR'
swapped_wires.add(result) if xor_conditions_met?(left, right, result, usage_map)
when 'AND'
swapped_wires.add(result) if and_conditions_met?(left, right, result, usage_map)
when 'OR'
swapped_wires.add(result) if or_conditions_met?(left, right, result, usage_map)
else
puts "Unknown operation: #{op} for gate #{gate}"
end
end
swapped_wires.to_a.sort
end
# Main Execution
wire_values, gates = parse_input('input.txt')
swapped_wires = identify_swapped_wires(wire_values, gates)
puts swapped_wires.join(',') | ruby |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | require 'set'
def parse_input(file)
wire_values = {}
gates = []
File.readlines(file).each do |line|
if line.include?("->")
# Parse gate operation like: "x0 AND y1 -> z45"
expr, wire = line.split(" -> ")
left, op, right = expr.split(" ")
# Store the gate operation in the gates list
gates << "#{left} #{op} #{right} -> #{wire}"
# Initialize wire values with nil as we don't know them yet
wire_values[wire] = nil
elsif line.include?(":")
# Parse initial wire values like: "x00: 1"
wire, value = line.split(": ")
wire_values[wire] = value.to_i
end
end
[wire_values, gates]
end
def collect_outputs(wire_values, prefix)
# Collects and returns a list of output values from a dictionary of wire values
# where the keys start with a given prefix.
wire_values.select { |key, _| key.start_with?(prefix) }
.sort
.map { |_key, value| value }
end
def is_input(operand)
# Checks if the given operand is an input variable.
operand[0] == 'x' || operand[0] == 'y'
end
def get_usage_map(gates)
# Generates a usage map from a list of gate strings.
usage_map = Hash.new { |hash, key| hash[key] = [] }
gates.each do |gate|
parts = gate.split(' ')
usage_map[parts[0]] << gate
usage_map[parts[2]] << gate
end
usage_map
end
def check_xor_conditions(left, right, result, usage_map)
# Checks if the given conditions for XOR operations are met.
if is_input(left)
if !is_input(right) || (result[0] == 'z' && result != 'z00')
return true
end
usage_ops = usage_map[result].map { |op| op.split(' ')[1] }
return result != 'z00' && usage_ops.sort != ['AND', 'XOR']
elsif result[0] != 'z'
return true
end
false
end
def check_and_conditions(left, right, result, usage_map)
# Checks specific conditions based on the provided inputs and usage map.
if is_input(left) && !is_input(right)
return true
end
usage_ops = usage_map[result].map { |op| op.split(' ')[1] }
usage_ops != ['OR']
end
def check_or_conditions(left, right, result, usage_map)
# Checks if the given conditions involving 'left', 'right', and 'result' meet certain criteria.
if is_input(left) || is_input(right)
return true
end
usage_ops = usage_map[result].map { |op| op.split(' ')[1] }
usage_ops.sort != ['AND', 'XOR']
end
def find_swapped_wires(wire_values, gates)
# Identifies and returns a list of swapped wires based on the provided wire values and gate operations.
usage_map = get_usage_map(gates)
swapped_wires = Set.new
gates.each do |gate|
left, op, right, _, result = gate.split(' ')
next if result == 'z45' || left == 'x00'
case op
when 'XOR'
swapped_wires.add(result) if check_xor_conditions(left, right, result, usage_map)
when 'AND'
swapped_wires.add(result) if check_and_conditions(left, right, result, usage_map)
when 'OR'
swapped_wires.add(result) if check_or_conditions(left, right, result, usage_map)
else
puts "#{gate} unknown op"
end
end
swapped_wires.to_a.sort
end
# Assuming input is in a file 'input.txt'
wire_values, gates = parse_input('input.txt')
swapped_wires = find_swapped_wires(wire_values, gates)
result = swapped_wires.join(',')
puts result | ruby |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | require 'set'
class Gate
attr_accessor :input_wires, :operation, :output_wire
def initialize(input_wires, operation, output_wire, wires)
@input_wires = input_wires
@operation = operation
@output_wire = output_wire
@wires = wires
end
def execute!
return unless @wires[@output_wire].nil?
return if @wires[@input_wires[0]].nil?
return if @wires[@input_wires[1]].nil?
if @operation == 'AND'
@wires[output_wire] = @wires[@input_wires[0]] & @wires[@input_wires[1]]
elsif @operation == 'OR'
@wires[output_wire] = @wires[@input_wires[0]] | @wires[@input_wires[1]]
else # XOR
@wires[output_wire] = @wires[@input_wires[0]] ^ @wires[@input_wires[1]]
end
end
end
def execute(gates)
while @wires.select { |key, _| key[0] == 'z' }.any? { |_, value| value.nil? }
gates.each(&:execute!)
end
result = 0
@wires.keys.select { |key| key[0] == 'z' }.sort.reverse_each do |key|
result <<= 1
result += @wires[key]
end
result
end
lines = File.readlines('day-24/input.txt').map(&:chomp)
gates_by_output_wire = {}
@wires = Hash.new(nil)
gates = Set[]
lines.reverse_each do |line|
if line.include?('->')
split_line = line.split(' ')
@wires[split_line[0]] = nil
@wires[split_line[2]] = nil
@wires[split_line[4]] = nil
gate = Gate.new([split_line[0], split_line[2]], split_line[1], split_line[4], @wires)
gates.add(gate)
gates_by_output_wire[split_line[4]] = gate
elsif line.include?(':')
split_line = line.split(': ')
@wires[split_line[0]] = split_line[1].to_i
end
end
execute(gates)
# Patterns in my input:
# X0 AND Y0 => A(kqn)
# X1 XOR Y1 => B(knr)
# A XOR B => Z1
# A AND B => C(fhg)
# C OR D => E(mkg)
# X1 AND Y1 => D(stk)
# X2 XOR Y2 => F(sbv)
# E XOR F => Z2
# E AND F => G(wwd)
# G OR H => I(gfq)
# X2 AND Y2 => H(mrq)
# X3 XOR Y3 => J(kfr)
# I XOR J => Z3
# I AND J => K(fdc)
# I'm assuming that this observed pattern is how the machine is "supposed" to be built, i.e. that there
# are no variances in the design as the bit count increases. (And more generally, that the machine isn't
# "spaghetti code".)
# (Therefore, this is not a "general solution" to the problem statement. But it does solve the problem
# for my input, at least!)
# So, every "level" except 0, 1, and the final one should have a pattern of 5 gates like the above two blocks
# (X==2 in this example):
#
# XN XOR YN => F
# E XOR F => ZN
# E AND F => G
# XN AND YN => H
# G OR H => I
# X(N+1) XOR Y(N+1) => J
# I XOR J => Z(N+1)
swap_gates = []
max_z = @wires.keys.select { |key| key[0] == 'z' }.map { |key| key[1..-1].to_i }.max
(2..(max_z - 2)).each do |bit|
xn = "x#{format('%02d', bit)}"
yn = "y#{format('%02d', bit)}"
zn = "z#{format('%02d', bit)}"
xn_plus_one = "x#{format('%02d', bit + 1)}"
yn_plus_one = "y#{format('%02d', bit + 1)}"
zn_plus_one = "z#{format('%02d', bit + 1)}"
gate_f = gates.find { |gate| gate.input_wires.tally == [xn, yn].tally && gate.operation == 'XOR' }
gate_z_n = gates.find { |gate| gate.input_wires.include?(gate_f.output_wire) && gate.operation == 'XOR' && gate.output_wire == zn }
next if gate_z_n.nil?
gate_g = gates.find { |gate| gate.input_wires.include?(gate_f.output_wire) && gate.operation == 'AND' }
gate_h = gates.find { |gate| gate.input_wires.tally == [xn, yn].tally && gate.operation == 'AND' }
gate_i = gates.find { |gate| gate.input_wires.tally == [gate_g.output_wire, gate_h.output_wire].tally && gate.operation == 'OR' }
gate_j = gates.find { |gate| gate.input_wires.tally == [xn_plus_one, yn_plus_one].tally && gate.operation == 'XOR' }
gate_z_n_plus_one = gates.find { |gate| gate.input_wires.tally == [gate_i.output_wire, gate_j.output_wire].tally && gate.operation == 'XOR' && gate.output_wire == zn_plus_one }
next unless gate_z_n_plus_one.nil?
swap_gate = gates.find { |gate| gate.input_wires.tally == [gate_i.output_wire, gate_j.output_wire].tally && gate.operation == 'XOR' }
if swap_gate
swap_gates << swap_gate.output_wire
swap_gates << zn_plus_one
else
swap_gates << gate_j.output_wire
other_swap_gate = gates.find { |gate| gate.input_wires.include?(gate_i.output_wire) && gate.operation == 'XOR' }
swap_gates << other_swap_gate.input_wires.find { |wire| wire != gate_i.output_wire }
end
end
p swap_gates.sort.join(',') | ruby |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | #!/usr/bin/env ruby
# Login to https://adventofcode.com/2024/day/25/input to download 'input.txt'.
# lines = readlines
# lines = File.readlines('sample.txt', chomp: true) # Answer: 3 (in 61 ms)
lines = File.readlines('input.txt', chomp: true) # Answer: 2950 (in 103 ms)
separators = lines.map.with_index { |line, i| line.empty? ? i : nil }.compact
schematic_ranges = ([-1] + separators + [lines.size]).each_cons(2).map { |pair| (pair.first + 1)...(pair.last) }
locks = schematic_ranges
.map { |range| lines[range] }
.select { |schematic| schematic[0].match(/^#+$/) && schematic[-1].match(/^\.+$/) }
.map do |schematic|
schematic[1...-1].map { |row| row.split('').map {|cell| cell == '#' ? 1 : 0 } }
end
.map do |positions|
(0...(positions.first.size)).collect { |col| positions.collect { |row| row[col] }.sum }
end
puts "Locks (#{locks.size})"
puts '-----'
locks.each { |lock| puts lock.inspect }
puts
keys = schematic_ranges
.map { |range| lines[range] }
.select { |schematic| schematic[0].match(/^\.+$/) && schematic[-1].match(/^#+$/) }
.map do |schematic|
schematic[1...-1].map { |row| row.split('').map {|cell| cell == '#' ? 1 : 0 } }
end
.map do |positions|
(0...(positions.first.size)).collect { |col| positions.collect { |row| row[col] }.sum }
end
puts "Keys (#{keys.size})"
puts '----'
keys.each { |key| puts key.inspect }
puts
answer = locks.product(keys).count do |lock, key|
lock.zip(key).map { |pair| pair.sum }.all? { |sum| sum <= 5 }
end
puts "Answer: #{answer}" | ruby |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | class Day25
def initialize()
@keys = []
@locks = []
@size = 7
end
def read_file
is_key = false
is_on_going = false
curr_line = 0
curr = [0,0,0,0,0]
read_lines = 1
File.open("Day25\\input25.txt", "r") do |f|
f.each_line.with_index do |line, i|
if !is_on_going && line.strip == "#####"
is_on_going = true
is_key = false # is lock
elsif is_on_going && read_lines == @size
is_on_going = false
if is_key
@keys.push(curr)
else
@locks.push(curr)
end
curr = [0,0,0,0,0]
read_lines = 1
elsif !is_on_going && line.strip == "....."
is_on_going = true
is_key = true # is key
end
if is_on_going
chars = line.strip.chars.map { |c| if c == "#" then 1 else 0 end}
curr = [curr[0] + chars[0], curr[1] + chars[1], curr[2] + chars[2], curr[3] + chars[3], curr[4] + chars[4]]
read_lines += 1
end
end
end
end
def get_matching_pairs
matches = 0
for i in 0..@keys.length-1
key = @keys[i]
for j in 0..@locks.length-1
lock = @locks[j]
matched_validations = 0
for k in 0..4
matched_validations += 1 if key[k] + lock[k] < @size
end
matches += 1 if matched_validations == 5
end
end
return matches
end
end
day25 = Day25.new()
day25.read_file
puts day25.get_matching_pairs | ruby |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | require 'matrix'
def parse_input(file)
input = File.read(File.join(File.dirname(__FILE__), file))
locks = []
keys = []
input.split("\n\n").each do |blk|
lk = Vector[0, 0, 0, 0, 0]
lock = blk[0] == '#'
rows = blk.lines[1..-2].map(&:strip)
rows.each do |row|
row.chars.each_with_index { |chr, idx| lk[idx] += 1 if chr == '#' }
end
if lock
locks.append(lk)
else
keys.append(lk)
end
end
[locks, keys]
end
def count_matches(file)
locks, keys = parse_input(file)
matches = 0
keys.each do |key|
locks.each do |lock|
matches += 1 unless (lock + key).any? { |pin| pin > 5 }
end
end
matches
end
puts count_matches('day25-input.txt') | ruby |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | locks,keys = File.read("Day25.txt").split("\n\n").map{|lock| lock.split("\n").map(&:chars).transpose}.group_by{|x| x[0][0]}.values
depth = locks[0][0].size
locks = locks.map{|lock|lock.map{|line| line.count('#')}}
keys = keys.map{|lock|lock.map{|line| line.count('#')}}
p locks.map{|lock| keys.map{|key| key.zip(lock).map{_1.inject(:+)}.all?{|x| x<=depth}}}.flatten.count(true) | ruby |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | #!/usr/bin/env ruby
# frozen_string_literal: true
file_path = File.expand_path('input.txt', __dir__)
input = File.read(file_path).split("\n\n").map { |line| line.split("\n").map(&:chars) }
keys = input.select { |line| line.first.all?{ |f| f == "." } && line.last.all?{ |f| f == "#" } }.map { |line| line.first(6).transpose.map { |line| line.count { |l| l == "#"} } }
locks = input.select { |line| line.first.all?{ |f| f == "#" } && line.last.all?{ |f| f == "." } }.map { |line| line.last(6).transpose.map { |line| line.count { |l| l == "#"} } }
cnt = 0
keys.each do |key|
locks.each do |lock|
match = true
key.each_with_index do |line, i|
if line + lock[i] > 5
match = false
break
end
end
cnt += 1 if match
end
end
puts cnt | ruby |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.