Skip to content

Instantly share code, notes, and snippets.

@tiegz
Last active December 11, 2018 06:18
Show Gist options
  • Save tiegz/7c4f8a82d9e5c14ff9864e67d74402d3 to your computer and use it in GitHub Desktop.
Save tiegz/7c4f8a82d9e5c14ff9864e67d74402d3 to your computer and use it in GitHub Desktop.
advent_of_code_2018.md
# --- Day 1: Chronal Calibration ---
# "We've detected some temporal anomalies," one of Santa's Elves at the Temporal Anomaly Research and Detection Instrument Station tells you. She sounded pretty worried when she called you down here. "At 500-year intervals into the past, someone has been changing Santa's history!"
# "The good news is that the changes won't propagate to our time stream for another 25 days, and we have a device" - she attaches something to your wrist - "that will let you fix the changes with no such propagation delay. It's configured to send you 500 years further into the past every few days; that was the best we could do on such short notice."
# "The bad news is that we are detecting roughly fifty anomalies throughout time; the device will indicate fixed anomalies with stars. The other bad news is that we only have one device and you're the best person for the job! Good lu--" She taps a button on the device and you suddenly feel like you're falling. To save Christmas, you need to get all fifty stars by December 25th.
# Collect stars by solving puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
# After feeling like you've been falling for a few minutes, you look at the device's tiny screen. "Error: Device must be calibrated before first use. Frequency drift detected. Cannot maintain destination lock." Below the message, the device shows a sequence of changes in frequency (your puzzle input). A value like +6 means the current frequency increases by 6; a value like -3 means the current frequency decreases by 3.
# For example, if the device displays frequency changes of +1, -2, +3, +1, then starting from a frequency of zero, the following changes would occur:
# Current frequency 0, change of +1; resulting frequency 1.
# Current frequency 1, change of -2; resulting frequency -1.
# Current frequency -1, change of +3; resulting frequency 2.
# Current frequency 2, change of +1; resulting frequency 3.
# In this example, the resulting frequency is 3.
# Here are other example situations:
# +1, +1, +1 results in 3
# +1, +1, -2 results in 0
# -1, -2, -3 results in -6
# Starting with a frequency of zero, what is the resulting frequency after all of the changes in frequency have been applied?
# To begin, get your puzzle input.
# Answer:
# You can also [Share] this puzzle.
# puts File.read("day1.txt").
# split("\n").
# map(&:to_i).
# reduce(0) { |memo, n|
# val = n[0] == "-" ? -(n.to_i ) : n.to_i
# memo = memo + val
# }
# Your puzzle answer was 595.
# The first half of this puzzle is complete! It provides one gold star: *
# --- Part Two ---
# You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.
# For example, using the same list of changes above, the device would loop as follows:
# Current frequency 0, change of +1; resulting frequency 1.
# Current frequency 1, change of -2; resulting frequency -1.
# Current frequency -1, change of +3; resulting frequency 2.
# Current frequency 2, change of +1; resulting frequency 3.
# (At this point, the device continues from the start of the list.)
# Current frequency 3, change of +1; resulting frequency 4.
# Current frequency 4, change of -2; resulting frequency 2, which has already been seen.
# In this example, the first frequency reached twice is 2. Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list.
# Here are other examples:
# +1, -1 first reaches 0 twice.
# +3, +3, +4, -2, -4 first reaches 10 twice.
# -6, +3, +8, +5, -6 first reaches 5 twice.
# +7, +7, -2, -7, -4 first reaches 14 twice.
# What is the first frequency your device reaches twice?
first_duped_frequency = nil
frequency_memo = 0
frequencies = {frequency_memo => true}
while first_duped_frequency.nil?
frequency_memo = File.read("day1.txt").
split("\n").
map(&:to_i).
reduce(frequency_memo) { |memo, n|
memo = memo + n.to_i
if first_duped_frequency.nil? && frequencies[memo.to_s] == true
first_duped_frequency = memo
end
frequencies[memo.to_s] = true
memo
}
end
puts first_duped_frequency
# 80598
# --- Day 2: Inventory Management System ---
# You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies.
# Outside the utility closet, you hear footsteps and a voice. "...I'm not sure either. But now that so many people have chimneys, maybe he could sneak in that way?" Another voice responds, "Actually, we've been working on a new kind of suit that would let him fit through tight spaces like that. But, I heard that a few days ago, they lost the prototype fabric, the design plans, everything! Nobody on the team can even seem to remember important details of the project!"
# "Wouldn't they have had enough fabric to fill several boxes in the warehouse? They'd be stored together, so the box IDs should be similar. Too bad it would take forever to search the warehouse for two similar box IDs..." They walk too far away to hear any more.
# Late at night, you sneak to the warehouse - who knows what kinds of paradoxes you could cause if you were discovered - and use your fancy wrist device to quickly scan every box and produce a list of the likely candidates (your puzzle input).
# To make sure you didn't miss any, you scan the likely candidate boxes again, counting the number that have an ID containing exactly two of any letter and then separately counting those with exactly three of any letter. You can multiply those two counts together to get a rudimentary checksum and compare it to what your device predicts.
# For example, if you see the following box IDs:
# abcdef contains no letters that appear exactly two or three times.
# bababc contains two a and three b, so it counts for both.
# abbcde contains two b, but no letter appears exactly three times.
# abcccd contains three c, but no letter appears exactly two times.
# aabcdd contains two a and two d, but it only counts once.
# abcdee contains two e.
# ababab contains three a and three b, but it only counts once.
# Of these box IDs, four of them contain a letter which appears exactly twice, and three of them contain a letter which appears exactly three times. Multiplying these together produces a checksum of 4 * 3 = 12.
# What is the checksum for your list of box IDs?
require 'pp'
lines_with_counts = File.read("day2.txt").
lines.
map { |line|
[
line,
line.strip.scan(/./).group_by { |i| i }.map { |k,v| [k, v.size] }.uniq
]
}
lines_with_two = lines_with_counts.select { |l|
l[1].any? { |i| i[1] == 2 }
}.size
lines_with_three = lines_with_counts.select { |l|
l[1].any? { |i| i[1] == 3 }
}.size
puts lines_with_two
puts lines_with_three
puts lines_with_two * lines_with_three
# Your puzzle answer was 5904.
# --- Part Two ---
# Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.
# The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs:
# abcde
# fghij
# klmno
# pqrst
# fguij
# axcye
# wvxyz
# The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes.
# What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.)
line_pairings_differing_by_one_character_by_position = File.read("day2.txt").
lines.combination(2).select { |a,b|
a = a.strip.scan(/./).map.with_index.to_a
b = b.strip.scan(/./).map.with_index.to_a
(a - b).size == 1
}
puts line_pairings_differing_by_one_character_by_position
# Your puzzle answer was jiwamotgsfrudclzbyzkhlrvp.
# Both parts of this puzzle are complete! They provide two gold stars: **
require 'pp'
# --- Day 3: No Matter How You Slice It ---
# The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit (thanks to someone who helpfully wrote its box IDs on the wall of the warehouse in the middle of the night). Unfortunately, anomalies are still affecting them - nobody can even agree on how to cut the fabric.
# The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
# Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
# The number of inches between the left edge of the fabric and the left edge of the rectangle.
# The number of inches between the top edge of the fabric and the top edge of the rectangle.
# The width of the rectangle in inches.
# The height of the rectangle in inches.
# A claim like #123 @ 3,2: 5x4 means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. Visually, it claims the square inches of fabric represented by # (and ignores the square inches of fabric represented by .) in the diagram below:
# ...........
# ...........
# ...#####...
# ...#####...
# ...#####...
# ...#####...
# ...........
# ...........
# ...........
# The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
# #1 @ 1,3: 4x4
# #2 @ 3,1: 4x4
# #3 @ 5,5: 2x2
# Visually, these claim the following areas:
# ........
# ...2222.
# ...2222.
# .11XX22.
# .11XX22.
# .111133.
# .111133.
# ........
# The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.)
# If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
w = 1000
h = 1000
fabric_matrix = w.times.to_a.map { |row|
h.times.to_a.map { |i|
nil
}
}
claims = File.read("day3.txt").lines.map(&:strip).
map { |line|
m = line.match(/\#(\d+) \@ (\d+)\,(\d+): (\d+)x(\d+)/)
{
line: line,
id: m[1].to_i,
x: m[2].to_i,
y: m[3].to_i,
width: m[4].to_i,
height: m[5].to_i
}
}.each { |claim|
claim[:height].times { |i|
y = claim[:y] + i
claim[:width].times { |j|
x = claim[:x] + j
(fabric_matrix[x][y] ||= []) << claim[:id]
}
}
}
num_of_sq_inches_with_overlapping_claims = 0
fabric_matrix.each do |row|
row.each do |col|
num_of_sq_inches_with_overlapping_claims += 1 if col && col.size > 1
end
end
puts "Answer 1: "
puts num_of_sq_inches_with_overlapping_claims
# Your puzzle answer was 110383.
# The first half of this puzzle is complete! It provides one gold star: *
# --- Part Two ---
# Amidst the chaos, you notice that exactly one claim doesn't overlap by even a single square inch of fabric with any other claim. If you can somehow draw attention to it, maybe the Elves will be able to make Santa's suit after all!
# For example, in the claims above, only claim 3 is intact after all claims are made.
# What is the ID of the only claim that doesn't overlap?
claims_that_dont_overlap = []
claims.select { |claim|
has_overlap = false
claim[:height].times { |i|
y = claim[:y] + i
claim[:width].times { |j|
x = claim[:x] + j
has_overlap = true if (fabric_matrix[x][y] - [claim[:id]]
).size > 0
}
}
claims_that_dont_overlap << claim if !has_overlap
}
puts "Answer 2: "
pp claims_that_dont_overlap.map { |c| c[:id] }
require 'pp'
# --- Day 4: Repose Record ---
# You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is as close as you can safely get.
# As you search the closet for anything that might help, you discover that you're not the first person to want to sneak in. Covering the walls, someone has spent an hour starting every midnight for the past few months secretly observing this guard post! They've been writing down the ID of the one guard on duty that night - the Elves seem to have decided that one guard was enough for the overnight shift - as well as when they fall asleep or wake up while at their post (your puzzle input).
# For example, consider the following records, which have already been organized into chronological order:
# [1518-11-01 00:00] Guard #10 begins shift
# [1518-11-01 00:05] falls asleep
# [1518-11-01 00:25] wakes up
# [1518-11-01 00:30] falls asleep
# [1518-11-01 00:55] wakes up
# [1518-11-01 23:58] Guard #99 begins shift
# [1518-11-02 00:40] falls asleep
# [1518-11-02 00:50] wakes up
# [1518-11-03 00:05] Guard #10 begins shift
# [1518-11-03 00:24] falls asleep
# [1518-11-03 00:29] wakes up
# [1518-11-04 00:02] Guard #99 begins shift
# [1518-11-04 00:36] falls asleep
# [1518-11-04 00:46] wakes up
# [1518-11-05 00:03] Guard #99 begins shift
# [1518-11-05 00:45] falls asleep
# [1518-11-05 00:55] wakes up
# Timestamps are written using year-month-day hour:minute format. The guard falling asleep or waking up is always the one whose shift most recently started. Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59) is relevant for those events.
# Visually, these records show that the guards are asleep at these times:
# Date ID Minute
# 000000000011111111112222222222333333333344444444445555555555
# 012345678901234567890123456789012345678901234567890123456789
# 11-01 #10 .....####################.....#########################.....
# 11-02 #99 ........................................##########..........
# 11-03 #10 ........................#####...............................
# 11-04 #99 ....................................##########..............
# 11-05 #99 .............................................##########.....
# The columns are Date, which shows the month-day portion of the relevant day; ID, which shows the guard on duty that day; and Minute, which shows the minutes during which the guard was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #.
# Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.
# If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick that guard into working tonight so you can have the best chance of sneaking in. You have two strategies for choosing the best guard/minute combination.
# Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most?
# In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day).
# While this example listed the entries in chronological order, your entries are in the order you found them. You'll need to organize them before they can be analyzed.
# What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 10 * 24 = 240.)
sorted_log = File.read("day4.txt").lines.map { |line|
_, y, m, d, h, min = *line.strip.match(/\[(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/)
[line.strip, Time.new(y.to_i, m.to_i, d.to_i, h.to_i, min.to_i)]
}.sort_by(&:last)
# pp sorted_log
minutes = (0..59).to_a
days = {}
cur_sleep_start = nil
cur_day = nil
sorted_log.each do |line, time|
_, id = *line.match(/Guard #(\d+)/)
if id
m, d = time.month, time.day
if time.hour == 23
d = d + 1 # They don't start sleepin til midnight
end
key = "#{m}-#{d}"
cur_day = (days["#{time.month}-#{time.day}"] = {
id: id,
minutes: (0..59).to_a.map { "." }
})
elsif line =~ /falls asleep/
raise "Unexpected" if cur_sleep_start
cur_sleep_start = time
elsif line =~ /wakes up/
(cur_sleep_start.min...time.min).each { |i|
cur_day[:minutes][i] = "#"
}
cur_sleep_start = nil
end
end
guards_sleep_time = {}
days.each { |k,v|
guards_sleep_time[v[:id]] ||= 0
guards_sleep_time[v[:id]] += v[:minutes].select { |c| c == "#" }.size
}
guard_id_who_sleeps_most = guards_sleep_time.sort_by(&:last).last.first
minutes_counts = (0..59).to_a.map { 0 }
days_of_guard_who_sleeps_most = days.
select { |k,v| v[:id] == guard_id_who_sleeps_most }
#pp days_of_guard_who_sleeps_most.map { |k,v| [k, v[:id], v[:minutes].join("")] }
days_of_guard_who_sleeps_most.
each { |k,v|
v[:minutes].each.with_index {|min, idx|
minutes_counts[idx] += 1 if min == "#"
}
}
max_count = minutes_counts.map.with_index.sort_by(&:first).last.first
most_slept_minute = minutes_counts.map.with_index.select { |count, min| count == 15 }.first.last
puts "Answer is #{guard_id_who_sleeps_most.to_i * most_slept_minute}"
# Your puzzle answer was 38813.
# The first half of this puzzle is complete! It provides one gold star: *
# --- Part Two ---
# Strategy 2: Of all guards, which guard is most frequently asleep on the same minute?
# In the example above, Guard #99 spent minute 45 asleep more than any other guard or minute - three times in total. (In all other cases, any guard spent any minute asleep at most twice.)
# What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 99 * 45 = 4455.)
minutes = {}
(0..59).map { |min|
days.each do |date, log|
minutes[min] ||= []
minutes[min] << log[:id].to_i if log[:minutes][min] == "#"
end
}
minutes_with_guard_id_counts = minutes.map { |min,guard_ids|
[
min,
guard_ids.group_by(&:itself).map { |k,v| [k, v.size] }.sort_by(&:last).to_h
]
}.sort_by { |min, guard_id_to_counts|
guard_id_to_counts.size > 0 ? guard_id_to_counts.values.last : 0
}
count_max = minutes_with_guard_id_counts.last.last.values.last
minute_with_guard_id_and_count = minutes_with_guard_id_counts.map { |min, guard_id_counts|
[min, guard_id_counts.select { |id, count| count >= count_max } ]
}.select { |min, guard_id_counts|
guard_id_counts.size > 0
}.sort_by(&:first).last
puts "Answer is #{minute_with_guard_id_and_count[0] * minute_with_guard_id_and_count[1].keys.first}"
# "Answer is 141071"
require 'pp'
# --- Day 5: Alchemical Reduction ---
# You've managed to sneak in to the prototype suit manufacturing lab. The Elves are making decent progress, but are still struggling with the suit's size reduction capabilities.
# While the very latest in 1518 alchemical technology might have solved their problem eventually, you can do better. You scan the chemical composition of the suit's material and discover that it is formed by extremely long polymers (one of which is available as your puzzle input).
# The polymer is formed by smaller units which, when triggered, react with each other such that two adjacent units of the same type and opposite polarity are destroyed. Units' types are represented by letters; units' polarity is represented by capitalization. For instance, r and R are units with the same type but opposite polarity, whereas r and s are entirely different types and do not react.
# For example:
# In aA, a and A react, leaving nothing behind.
# In abBA, bB destroys itself, leaving aA. As above, this then destroys itself, leaving nothing.
# In abAB, no two adjacent units are of the same type, and so nothing happens.
# In aabAAB, even though aa and AA are of the same type, their polarities match, and so nothing happens.
# Now, consider a larger example, dabAcCaCBAcCcaDA:
# dabAcCaCBAcCcaDA The first 'cC' is removed.
# dabAaCBAcCcaDA This creates 'Aa', which is removed.
# dabCBAcCcaDA Either 'cC' or 'Cc' are removed (the result is the same).
# dabCBAcaDA No further actions can be taken.
# After all possible reactions, the resulting polymer contains 10 units.
# How many units remain after fully reacting the polymer you scanned? (Note: in this puzzle and others, the input is large; if you copy/paste your input, make sure you get the whole thing.)
def count_of_polymers_after_reactions(units)
mutated = true
while mutated
mutated = false
units.each.with_index { |char, idx|
next_char = units[idx + 1]
if next_char && char && (char != next_char) && (char == next_char.upcase || next_char == char.upcase)
units[idx] = nil
units[idx + 1] = nil
mutated = true
end
}
units.compact!
end
units.size
end
units = File.read("day5.txt").strip
size = count_of_polymers_after_reactions(units.chars)
puts "Answer #1: the size after polymer reactions is #{size}."
# Your puzzle answer was 10598.
# part 2
# --- Part Two ---
# Time to improve the polymer.
# One of the unit types is causing problems; it's preventing the polymer from collapsing as much as it should. Your goal is to figure out which unit type is causing the most problems, remove all instances of it (regardless of polarity), fully react the remaining polymer, and measure its length.
# For example, again using the polymer dabAcCaCBAcCcaDA from above:
# Removing all A/a units produces dbcCCBcCcD. Fully reacting this polymer produces dbCBcD, which has length 6.
# Removing all B/b units produces daAcCaCAcCcaDA. Fully reacting this polymer produces daCAcaDA, which has length 8.
# Removing all C/c units produces dabAaBAaDA. Fully reacting this polymer produces daDA, which has length 4.
# Removing all D/d units produces abAcCaCBAcCcaA. Fully reacting this polymer produces abCBAc, which has length 6.
# In this example, removing all C/c units was best, producing the answer 4.
# What is the length of the shortest polymer you can produce by removing all units of exactly one type and fully reacting the result?
units_with_counts = ("a".."z").to_a.map { |char|
units_without_chars = units.gsub(/#{char}/i, "")
result_size = count_of_polymers_after_reactions(units_without_chars.chars)
[char, result_size]
}.sort_by(&:last)
puts "Answer #2: unit is #{units_with_counts.first.first} with #{units_with_counts.first.last} size."
require 'pp'
# --- Day 6: Chronal Coordinates ---
# The device on your wrist beeps several times, and once again you feel like you're falling.
# "Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates."
# The device then produces a list of coordinates (your puzzle input). Are they places it thinks are safe or dangerous? It recommends you check manual page 729. The Elves did not give you a manual.
# If they're dangerous, maybe you can minimize the danger by finding the coordinate that gives the largest distance from the other points.
# Using only the Manhattan distance, determine the area around each coordinate by counting the number of integer X,Y locations that are closest to that coordinate (and aren't tied in distance to any other coordinate).
# Your goal is to find the size of the largest area that isn't infinite. For example, consider the following list of coordinates:
# 1, 1
# 1, 6
# 8, 3
# 3, 4
# 5, 5
# 8, 9
# If we name these coordinates A through F, we can draw them on a grid, putting 0,0 at the top left:
# ..........
# .A........
# ..........
# ........C.
# ...D......
# .....E....
# .B........
# ..........
# ..........
# ........F.
# This view is partial - the actual grid extends infinitely in all directions. Using the Manhattan distance, each location's closest coordinate can be determined, shown here in lowercase:
# aaaaa.cccc
# aAaaa.cccc
# aaaddecccc
# aadddeccCc
# ..dDdeeccc
# bb.deEeecc
# bBb.eeee..
# bbb.eeefff
# bbb.eeffff
# bbb.ffffFf
# Locations shown as . are equally far from two or more coordinates, and so they don't count as being closest to any.
# In this example, the areas of coordinates A, B, C, and F are infinite - while not shown here, their areas extend forever outside the visible grid. However, the areas of coordinates D and E are finite: D is closest to 9 locations, and E is closest to 17 (both including the coordinate's location itself). Therefore, in this example, the size of the largest area is 17.
# What is the size of the largest area that isn't infinite?
# Your puzzle answer was 3620.
# Computes manhattan distance btwn two points
def distance(x1, y1, x2, y2)
(x1 - x2).abs + (y1 - y2).abs
end
coords = File.read("day6.txt").lines.to_a.map.with_index do |line, idx|
[idx.to_s, line.split(',').map(&:strip).map(&:to_i)]
end.to_h
max_x = coords.map { |label, (x,y)| x }.sort.last + 1 # Not sure why puzzle example padded right side with 1 extra col?
max_y = coords.map { |label, (x,y)| y }.sort.last
grid = (0..max_y).map { |row| (0..max_x).map { "." } }
coords.each { |label, (x,y)| grid[y][x] = label }
grid_with_dangerous_matches = grid.map.with_index { |row, grid_y|
row.map.with_index { |cell, grid_x|
if coord = coords.find { |label, (x,y)| x == grid_x && y == grid_y }
"#{coord.first}"
else
distances = coords.map { |label, (coord_x, coord_y)|
[label, distance(coord_x, coord_y, grid_x, grid_y)]
}.sort_by(&:last)
if distances[0][1] == distances[1][1] # coord has a tie
"."
else
distances.sort_by(&:last).first.first.downcase
end
end
}
}
# Debug grid
# puts grid_with_dangerous_matches.map { |row| row.map { |col| col }.join("") }.join("\n")
infinite_letters = grid_with_dangerous_matches[0].flatten.uniq + # top
grid_with_dangerous_matches[-1].flatten.uniq + # bottom
grid_with_dangerous_matches.map { |row| [row[0], row[-1]] }.flatten.uniq # left and right
infinite_letters = infinite_letters.uniq - ["."]
finite_letters = coords.map(&:first) - infinite_letters
biggest_finite_coordinate_area = coords.slice(*finite_letters).map { |label, (x,y)|
grid_with_dangerous_matches.map { |row| row.count { |cell| cell == label } }.sum
}.sort.last
puts "The answer to Part 1 is #{biggest_finite_coordinate_area}"
# Your puzzle answer was 3620.
# The first half of this puzzle is complete! It provides one gold star: *
# --- Part Two ---
# On the other hand, if the coordinates are safe, maybe the best you can do is try to find a region near as many coordinates as possible.
# For example, suppose you want the sum of the Manhattan distance to all of the coordinates to be less than 32. For each location, add up the distances to all of the given coordinates; if the total of those distances is less than 32, that location is within the desired region. Using the same coordinates as above, the resulting region looks like this:
# ..........
# .A........
# ..........
# ...###..C.
# ..#D###...
# ..###E#...
# .B.###....
# ..........
# ..........
# ........F.
# In particular, consider the highlighted location 4,3 located at the top middle of the region. Its calculation is as follows, where abs() is the absolute value function:
# Distance to coordinate A: abs(4-1) + abs(3-1) = 5
# Distance to coordinate B: abs(4-1) + abs(3-6) = 6
# Distance to coordinate C: abs(4-8) + abs(3-3) = 4
# Distance to coordinate D: abs(4-3) + abs(3-4) = 2
# Distance to coordinate E: abs(4-5) + abs(3-5) = 3
# Distance to coordinate F: abs(4-8) + abs(3-9) = 10
# Total distance: 5 + 6 + 4 + 2 + 3 + 10 = 30
# Because the total distance to all coordinates (30) is less than 32, the location is within the region.
# This region, which also includes coordinates D and E, has a total size of 16.
# Your actual region will need to be much larger than this example, though, instead including all locations with a total distance of less than 10000.
# What is the size of the region containing all locations which have a total distance to all given coordinates of less than 10000?
SAFETY_THRESHHOLD = 10_000
grid_with_safe_matches = grid.map.with_index { |row, grid_y|
row.map.with_index { |cell, grid_x|
if coord = coords.find { |label, (x,y)| x == grid_x && y == grid_y }
"#{coord.first}"
else
distances = coords.map { |label, (coord_x, coord_y)|
[label, distance(coord_x, coord_y, grid_x, grid_y)]
}.sort_by(&:last)
if distances.map(&:last).sum < SAFETY_THRESHHOLD
"#" # tie
else
"."
end
end
}
}
# Debug grid
# puts grid_with_safe_matches.map { |row| row.map { |col| col }.join("") }.join("\n")
in_region, count = false, 0
grid_with_safe_matches.each { |row|
row.each { |col|
if !in_region && (col == "#")
in_region = true
count += 1
elsif in_region && col == "."
in_region = false
elsif in_region
count += 1
end
}
}
puts "The answer to Part 2 is #{count}"
# 39930
require 'set'
require 'pp'
# --- Day 7: The Sum of Its Parts ---
# You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you decide to risk creating a paradox by asking them for directions.
# "Oh, are you the search party?" Somehow, you can understand whatever Elves from the year 1018 speak; you assume it's Ancient Nordic Elvish. Could the device on your wrist also be a translator? "Those clothes don't look very warm; take this." They hand you a heavy coat.
# "We do need to find our way back to the North Pole, but we have higher priorities at the moment. You see, believe it or not, this box contains something that will solve all of Santa's transportation problems - at least, that's what it looks like from the pictures in the instructions." It doesn't seem like they can read whatever language it's in, but you can: "Sleigh kit. Some assembly required."
# "'Sleigh'? What a wonderful name! You must help us assemble this 'sleigh' at once!" They start excitedly pulling more parts out of the box.
# The instructions specify a series of steps and requirements about which steps must be finished before others can begin (your puzzle input). Each step is designated by a single letter. For example, suppose you have the following instructions:
# Step C must be finished before step A can begin.
# Step C must be finished before step F can begin.
# Step A must be finished before step B can begin.
# Step A must be finished before step D can begin.
# Step B must be finished before step E can begin.
# Step D must be finished before step E can begin.
# Step F must be finished before step E can begin.
# Visually, these requirements look like this:
# -->A--->B--
# / \ \
# C -->D----->E
# \ /
# ---->F-----
# Your first goal is to determine the order in which the steps should be completed. If more than one step is ready, choose the step which is first alphabetically. In this example, the steps would be completed as follows:
# Only C is available, and so it is done first.
# Next, both A and F are available. A is first alphabetically, so it is done next.
# Then, even though F was available earlier, steps B and D are now also available, and B is the first alphabetically of the three.
# After that, only D and F are available. E is not available because only some of its prerequisites are complete. Therefore, D is completed next.
# F is the only choice, so it is done next.
# Finally, E is completed.
# So, in this example, the correct order is CABDFE.
# In what order should the steps in your instructions be completed?
order = []
points = {}
File.read("day7.txt").lines.each { |line|
match, prereq_point, point = *line.strip.match(/Step (.*) must be finished before step (.*) can begin\./)
(points[point] ||= Set.new) << prereq_point
}
WALKED_POINTS = points.dup
def get_points_with_no_prereqs
WALKED_POINTS.values.map(&:to_a).flatten.uniq - WALKED_POINTS.keys
end
s = get_points_with_no_prereqs.sort
while s.size > 0
s = s.sort
n = s.shift
order << n
WALKED_POINTS.select { |k,v| v.include?(n) }.each do |m, v|
v.delete(n)
if WALKED_POINTS[m].size == 0
s << m
end
end
end
puts "Order was #{order.uniq.join('')}"
# Your puzzle answer was EFHLMTKQBWAPGIVXSZJRDUYONC.
# The first half of this puzzle is complete! It provides one gold star: *
# --- Part Two ---
# As you're about to begin construction, four of the Elves offer to help. "The sun will set soon; it'll go faster if we work together." Now, you need to account for multiple people working on steps simultaneously. If multiple steps are available, workers should still begin them in alphabetical order.
# Each step takes 60 seconds plus an amount corresponding to its letter: A=1, B=2, C=3, and so on. So, step A takes 60+1=61 seconds, while step Z takes 60+26=86 seconds. No time is required between steps.
# To simplify things for the example, however, suppose you only have help from one Elf (a total of two workers) and that each step takes 60 fewer seconds (so that step A takes 1 second and step Z takes 26 seconds). Then, using the same instructions as above, this is how each second would be spent:
# Second Worker 1 Worker 2 Done
# 0 C .
# 1 C .
# 2 C .
# 3 A F C
# 4 B F CA
# 5 B F CA
# 6 D F CAB
# 7 D F CAB
# 8 D F CAB
# 9 D . CABF
# 10 E . CABFD
# 11 E . CABFD
# 12 E . CABFD
# 13 E . CABFD
# 14 E . CABFD
# 15 . . CABFDE
# Each row represents one second of time. The Second column identifies how many seconds have passed as of the beginning of that second. Each worker column shows the step that worker is currently doing (or . if they are idle). The Done column shows completed steps.
# Note that the order of the steps has changed; this is because steps now take time to finish and multiple workers can begin multiple steps simultaneously.
# In this example, it would take 15 seconds for two workers to complete these steps.
# With 5 workers and the 60+ second step durations described above, how long will it take to complete all of the steps?
WORKERS = 6.times
BASE_TIME = 60
ALPHABET = ("A".."Z").map.with_index.map { |k,v| [k, v + 1]}.to_h
points = {}
File.read("day7.txt").lines.each { |line|
match, prereq_point, point = *line.strip.match(/Step (.*) must be finished before step (.*) can begin\./)
(points[point] ||= Set.new) << prereq_point
}
WALKED_POINTS = points.dup
order = []
seconds = 0
s = get_points_with_no_prereqs.sort
QUEUE = WORKERS.map { |worker|
if n = s.shift
[worker, n, BASE_TIME + ALPHABET[n]]
else
[worker, nil, 0]
end
}
while s.size > 0 || QUEUE.map(&:last).sum > 0
#puts "#{seconds}\t" + QUEUE.map { |a,b,c| [b,c].join('-') }.join("\t") + "\t#{order.join('')}"
QUEUE.each.with_index do |(worker, n, time_left), idx|
if time_left > 0
QUEUE[idx][2] -= 1
end
if QUEUE[idx][2].zero?
WALKED_POINTS.select { |k,v| v.include?(n) }.each do |m, v|
WALKED_POINTS[m].delete(n)
if WALKED_POINTS[m].size == 0
s << m
end
end
order << n #unless order.include?(n)
s = s.sort
if n = s.shift
QUEUE[idx] = [worker, n, BASE_TIME + ALPHABET[n]]
else
QUEUE[idx][1] = nil
end
end
end
seconds += 1
end
#puts "#{seconds}\t" + QUEUE.map { |a,b,c| [b,c].join('-') }.join("\t") + "\t#{order.join('')}"
puts "The answer is #{seconds - 1}"
# Answer is 1056
require 'pp'
# --- Day 8: Memory Maneuver ---
# The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here.
# You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: "Failed to start navigation system. Could not read software license file."
# The navigation system's license file consists of a list of numbers (your puzzle input). The numbers define a data structure which, when processed, produces some kind of tree that can be used to calculate the license number.
# The tree is made up of nodes; a single, outermost node forms the tree's root, and it contains all other nodes in the tree (or contains nodes that contain nodes, and so on).
# Specifically, a node consists of:
# A header, which is always exactly two numbers:
# The quantity of child nodes.
# The quantity of metadata entries.
# Zero or more child nodes (as specified in the header).
# One or more metadata entries (as specified in the header).
# Each child node is itself a node that has its own header, child nodes, and metadata. For example:
# 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
# A----------------------------------
# B----------- C-----------
# D-----
# In this example, each node of the tree is also marked with an underline starting with a letter for easier identification. In it, there are four nodes:
# A, which has 2 child nodes (B, C) and 3 metadata entries (1, 1, 2).
# B, which has 0 child nodes and 3 metadata entries (10, 11, 12).
# C, which has 1 child node (D) and 1 metadata entry (2).
# D, which has 0 child nodes and 1 metadata entry (99).
# The first check done on the license file is to simply add up all of the metadata entries. In this example, that sum is 1+1+2+10+11+12+2+99=138.
# What is the sum of all metadata entries?
# Your puzzle answer was 46096.
current_label = "A"
nums = File.read("day8.txt").split.map(&:to_i)
take_node = ->() {
{
label: current_label,
num_children: nums.shift,
num_metadata: nums.shift,
children: [],
metadata: []
}.tap { current_label.next! }
}
process_node = ->(node) {
node[:num_children].times do
take_node.call.tap do |child_node|
process_node[child_node]
node[:children] << child_node
end
end
node[:num_metadata].times do
node[:metadata] << nums.shift
end
}
sum_of_metadata = ->(node) {
node[:metadata].sum +
node[:children].map { |child|
sum_of_metadata[child]
}.sum
}
ROOT_NODE = take_node.call
node = ROOT_NODE
while nums.size > 0
process_node[node]
node = take_node.call
end
puts sum_of_metadata.call(ROOT_NODE)
# The answer to Part One is 46096
# --- Part Two ---
# The second check is slightly more complicated: you need to find the value of the root node (A in the example above).
# The value of a node depends on whether it has child nodes.
# If a node has no child nodes, its value is the sum of its metadata entries. So, the value of node B is 10+11+12=33, and the value of node D is 99.
# However, if a node does have child nodes, the metadata entries become indexes which refer to those child nodes. A metadata entry of 1 refers to the first child node, 2 to the second, 3 to the third, and so on. The value of this node is the sum of the values of the child nodes referenced by the metadata entries. If a referenced child node does not exist, that reference is skipped. A child node can be referenced multiple time and counts each time it is referenced. A metadata entry of 0 does not refer to any child node.
# For example, again using the above nodes:
# Node C has one metadata entry, 2. Because node C has only one child node, 2 references a child node which does not exist, and so the value of node C is 0.
# Node A has three metadata entries: 1, 1, and 2. The 1 references node A's first child node, B, and the 2 references node A's second child node, C. Because node B has a value of 33 and node C has a value of 0, the value of node A is 33+33+0=66.
# So, in this example, the value of the root node is 66.
# What is the value of the root node?
sum_of_node_values = ->(node) {
val = if node[:children].size.zero?
node[:metadata].sum
else
node[:metadata].map { |idx|
node[:children][idx - 1].yield_self { |child|
child ? sum_of_node_values.call(child) : 0
}
}.sum
end
}
puts sum_of_node_values.call(ROOT_NODE)
# The answer to Part two is 24820
require 'pp'
_match, PLAYERS, MAX_MARBLES = *File.read("day9.txt").match(/(\d+) players; last marble is worth (\d+) points/)
class Marble
attr_accessor :backward, :forward, :val
def initialize(backward = nil, forward = nil, val = nil)
self.backward, self.forward, self.val = backward, forward, val
end
def self.insert_between(b, f, val)
Marble.new(b, f, val).tap do |m|
b.forward = m
f.backward = m
end
end
def remove
self.backward.forward = self.forward
self.forward.backward = self.backward
[self, self.forward]
end
end
def solve_for(players, max_marbles)
marbles = Marble.new.tap do |root|
root.backward = root
root.forward = root
root.val = 0
end
current_marble = marbles
current_player = 0
scores = players.times.to_a.map { 0 }
(1...max_marbles).each do |i|
puts i if i % 10000 == 0
if i % 23 == 0
scores[current_player] += i
replaced_marble, current_marble = current_marble.backward.backward.backward.backward.backward.backward.backward.remove
scores[current_player] += replaced_marble.val
else
current_marble = Marble.insert_between(current_marble.forward, current_marble.forward.forward, i)
end
current_player = (current_player + 1) % players
end
scores.max
end
# --- Day 9: Marble Mania ---
# You talk to the Elves while you wait for your navigation system to initialize. To pass the time, they introduce you to their favorite marble game.
# The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.
# First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble.
# Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble.
# However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
# For example, suppose there are 9 players. After the marble with value 0 is placed in the middle, each player (shown in square brackets) takes a turn. The result of each of those turns would produce circles of marbles like this, where clockwise is to the right and the resulting current marble is in parentheses:
# [-] (0)
# [1] 0 (1)
# [2] 0 (2) 1
# [3] 0 2 1 (3)
# [4] 0 (4) 2 1 3
# [5] 0 4 2 (5) 1 3
# [6] 0 4 2 5 1 (6) 3
# [7] 0 4 2 5 1 6 3 (7)
# [8] 0 (8) 4 2 5 1 6 3 7
# [9] 0 8 4 (9) 2 5 1 6 3 7
# [1] 0 8 4 9 2(10) 5 1 6 3 7
# [2] 0 8 4 9 2 10 5(11) 1 6 3 7
# [3] 0 8 4 9 2 10 5 11 1(12) 6 3 7
# [4] 0 8 4 9 2 10 5 11 1 12 6(13) 3 7
# [5] 0 8 4 9 2 10 5 11 1 12 6 13 3(14) 7
# [6] 0 8 4 9 2 10 5 11 1 12 6 13 3 14 7(15)
# [7] 0(16) 8 4 9 2 10 5 11 1 12 6 13 3 14 7 15
# [8] 0 16 8(17) 4 9 2 10 5 11 1 12 6 13 3 14 7 15
# [9] 0 16 8 17 4(18) 9 2 10 5 11 1 12 6 13 3 14 7 15
# [1] 0 16 8 17 4 18 9(19) 2 10 5 11 1 12 6 13 3 14 7 15
# [2] 0 16 8 17 4 18 9 19 2(20)10 5 11 1 12 6 13 3 14 7 15
# [3] 0 16 8 17 4 18 9 19 2 20 10(21) 5 11 1 12 6 13 3 14 7 15
# [4] 0 16 8 17 4 18 9 19 2 20 10 21 5(22)11 1 12 6 13 3 14 7 15
# [5] 0 16 8 17 4 18(19) 2 20 10 21 5 22 11 1 12 6 13 3 14 7 15
# [6] 0 16 8 17 4 18 19 2(24)20 10 21 5 22 11 1 12 6 13 3 14 7 15
# [7] 0 16 8 17 4 18 19 2 24 20(25)10 21 5 22 11 1 12 6 13 3 14 7 15
# The goal is to be the player with the highest score after the last marble is used up. Assuming the example above ends after the marble numbered 25, the winning score is 23+9=32 (because player 5 kept marble 23 and removed marble 9, while no other player got any points in this very short example game).
# Here are a few more examples:
# 10 players; last marble is worth 1618 points: high score is 8317
# 13 players; last marble is worth 7999 points: high score is 146373
# 17 players; last marble is worth 1104 points: high score is 2764
# 21 players; last marble is worth 6111 points: high score is 54718
# 30 players; last marble is worth 5807 points: high score is 37305
# What is the winning Elf's score?
# Your puzzle answer was 439089.
# puts solve_for(9, 27) # Test data
answer = solve_for(PLAYERS.to_i, MAX_MARBLES.to_i)
puts "The answer to Part 1 (#{PLAYERS}, #{MAX_MARBLES}) is #{answer}"
# The answer to Part 1 is 439089
# --- Part Two ---
# Amused by the speed of your answer, the Elves are curious:
# What would the new winning Elf's score be if the number of the last marble were 100 times larger?
answer = solve_for(PLAYERS.to_i, MAX_MARBLES.to_i * 100)
puts "The answer to Part 2 is #{answer}"
# The answer to Part 2 is 3668541094
require 'pp'
# --- Day 10: The Stars Align ---
# It's no use; your navigation system simply isn't capable of providing walking directions in the arctic circle, and certainly not in 1018.
# The Elves suggest an alternative. In times like these, North Pole rescue operations will arrange points of light in the sky to guide missing Elves back to base. Unfortunately, the message is easy to miss: the points move slowly enough that it takes hours to align them, but have so much momentum that they only stay aligned for a second. If you blink at the wrong time, it might be hours before another message appears.
# You can see these points of light floating in the distance, and record their position in the sky and their velocity, the relative change in position per second (your puzzle input). The coordinates are all given from your perspective; given enough time, those positions and velocities will move the points into a cohesive message!
# Rather than wait, you decide to fast-forward the process and calculate what the points will eventually spell.
# For example, suppose you note the following points:
# position=< 9, 1> velocity=< 0, 2>
# position=< 7, 0> velocity=<-1, 0>
# position=< 3, -2> velocity=<-1, 1>
# position=< 6, 10> velocity=<-2, -1>
# position=< 2, -4> velocity=< 2, 2>
# position=<-6, 10> velocity=< 2, -2>
# position=< 1, 8> velocity=< 1, -1>
# position=< 1, 7> velocity=< 1, 0>
# position=<-3, 11> velocity=< 1, -2>
# position=< 7, 6> velocity=<-1, -1>
# position=<-2, 3> velocity=< 1, 0>
# position=<-4, 3> velocity=< 2, 0>
# position=<10, -3> velocity=<-1, 1>
# position=< 5, 11> velocity=< 1, -2>
# position=< 4, 7> velocity=< 0, -1>
# position=< 8, -2> velocity=< 0, 1>
# position=<15, 0> velocity=<-2, 0>
# position=< 1, 6> velocity=< 1, 0>
# position=< 8, 9> velocity=< 0, -1>
# position=< 3, 3> velocity=<-1, 1>
# position=< 0, 5> velocity=< 0, -1>
# position=<-2, 2> velocity=< 2, 0>
# position=< 5, -2> velocity=< 1, 2>
# position=< 1, 4> velocity=< 2, 1>
# position=<-2, 7> velocity=< 2, -2>
# position=< 3, 6> velocity=<-1, -1>
# position=< 5, 0> velocity=< 1, 0>
# position=<-6, 0> velocity=< 2, 0>
# position=< 5, 9> velocity=< 1, -2>
# position=<14, 7> velocity=<-2, 0>
# position=<-3, 6> velocity=< 2, -1>
# Each line represents one point. Positions are given as <X, Y> pairs: X represents how far left (negative) or right (positive) the point appears, while Y represents how far up (negative) or down (positive) the point appears.
# At 0 seconds, each point has the position given. Each second, each point's velocity is added to its position. So, a point with velocity <1, -2> is moving to the right, but is moving upward twice as quickly. If this point's initial position were <3, 9>, after 3 seconds, its position would become <6, 3>.
# Over time, the points listed above would move like this:
# Initially:
# ........#.............
# ................#.....
# .........#.#..#.......
# ......................
# #..........#.#.......#
# ...............#......
# ....#.................
# ..#.#....#............
# .......#..............
# ......#...............
# ...#...#.#...#........
# ....#..#..#.........#.
# .......#..............
# ...........#..#.......
# #...........#.........
# ...#.......#..........
# After 1 second:
# ......................
# ......................
# ..........#....#......
# ........#.....#.......
# ..#.........#......#..
# ......................
# ......#...............
# ....##.........#......
# ......#.#.............
# .....##.##..#.........
# ........#.#...........
# ........#...#.....#...
# ..#...........#.......
# ....#.....#.#.........
# ......................
# ......................
# After 2 seconds:
# ......................
# ......................
# ......................
# ..............#.......
# ....#..#...####..#....
# ......................
# ........#....#........
# ......#.#.............
# .......#...#..........
# .......#..#..#.#......
# ....#....#.#..........
# .....#...#...##.#.....
# ........#.............
# ......................
# ......................
# ......................
# After 3 seconds:
# ......................
# ......................
# ......................
# ......................
# ......#...#..###......
# ......#...#...#.......
# ......#...#...#.......
# ......#####...#.......
# ......#...#...#.......
# ......#...#...#.......
# ......#...#...#.......
# ......#...#..###......
# ......................
# ......................
# ......................
# ......................
# After 4 seconds:
# ......................
# ......................
# ......................
# ............#.........
# ........##...#.#......
# ......#.....#..#......
# .....#..##.##.#.......
# .......##.#....#......
# ...........#....#.....
# ..............#.......
# ....#......#...#......
# .....#.....##.........
# ...............#......
# ...............#......
# ......................
# ......................
# After 3 seconds, the message appeared briefly: HI. Of course, your message will be much longer and will take many more seconds to appear.
# What message will eventually appear in the sky?
# Your puzzle answer was ECKXJLJF.
Point = Struct.new(:px, :py, :vx, :vy) do
def tick
self.px = px + vx
self.py = py + vy
end
end
points = File.read("day10.txt").lines.map { |line|
match, p, v = *line.strip.match(/position=<(.*)> velocity=<(.*)>/)
px, py = p.split(',').map(&:strip).map(&:to_i)
vx, vy = v.split(',').map(&:strip).map(&:to_i)
Point.new(px, py, vx, vy)
}
puts points
GRID_SIZE = points.size * 2
SIZE_ADJUSTMENT = points.size
$i = 0
SIZE_THRESHHOLD = points.size
def draw(points)
if (size = points.select { |p| p.px.abs < SIZE_ADJUSTMENT && p.py.abs < SIZE_ADJUSTMENT }.size) == points.size
map = GRID_SIZE.times.to_a.map { GRID_SIZE.times.to_a.map { "." } }
points.each { |p|
if map[p.py + SIZE_ADJUSTMENT] && map[p.py + SIZE_ADJUSTMENT][p.px + SIZE_ADJUSTMENT]
ap[p.py + SIZE_ADJUSTMENT][p.px + SIZE_ADJUSTMENT] = "#"
end
}
puts $i
puts map.map(&:join).join("\n")
sleep 0.5
end
$i += 1
end
draw(points)
while true
points.map(&:tick)
draw(points)
end
# The puzzle answer was ECKXJLJF
# --- Part Two ---
# Good thing you didn't have to wait, because that would have taken a long time - much longer than the 3 seconds in the example above.
# Impressed by your sub-hour communication capabilities, the Elves are curious: exactly how many seconds would they have needed to wait for that message to appear?
# Your puzzle answer was 10880.
require 'pp'
# --- Day 11: Chronal Charge ---
# You watch the Elves and their sleigh fade into the distance as they head toward the North Pole.
# Actually, you're the one fading. The falling sensation returns.
# The low fuel warning light is illuminated on your wrist-mounted device. Tapping it once causes it to project a hologram of the situation: a 300x300 grid of fuel cells and their current power levels, some negative. You're not sure what negative power means in the context of time travel, but it can't be good.
# Each fuel cell has a coordinate ranging from 1 to 300 in both the X (horizontal) and Y (vertical) direction. In X,Y notation, the top-left cell is 1,1, and the top-right cell is 300,1.
# The interface lets you select any 3x3 square of fuel cells. To increase your chances of getting to your destination, you decide to choose the 3x3 square with the largest total power.
# The power level in a given fuel cell can be found through the following process:
# Find the fuel cell's rack ID, which is its X coordinate plus 10.
# Begin with a power level of the rack ID times the Y coordinate.
# Increase the power level by the value of the grid serial number (your puzzle input).
# Set the power level to itself multiplied by the rack ID.
# Keep only the hundreds digit of the power level (so 12345 becomes 3; numbers with no hundreds digit become 0).
# Subtract 5 from the power level.
# For example, to find the power level of the fuel cell at 3,5 in a grid with serial number 8:
# The rack ID is 3 + 10 = 13.
# The power level starts at 13 * 5 = 65.
# Adding the serial number produces 65 + 8 = 73.
# Multiplying by the rack ID produces 73 * 13 = 949.
# The hundreds digit of 949 is 9.
# Subtracting 5 produces 9 - 5 = 4.
# So, the power level of this fuel cell is 4.
# Here are some more example power levels:
# Fuel cell at 122,79, grid serial number 57: power level -5.
# Fuel cell at 217,196, grid serial number 39: power level 0.
# Fuel cell at 101,153, grid serial number 71: power level 4.
# Your goal is to find the 3x3 square which has the largest total power. The square must be entirely within the 300x300 grid. Identify this square using the X,Y coordinate of its top-left fuel cell. For example:
# For grid serial number 18, the largest total 3x3 square has a top-left corner of 33,45 (with a total power of 29); these fuel cells appear in the middle of this 5x5 region:
# -2 -4 4 4 4
# -4 4 4 4 -5
# 4 3 3 4 -4
# 1 1 2 4 -3
# -1 0 2 -5 -2
# For grid serial number 42, the largest 3x3 square's top-left is 21,61 (with a total power of 30); they are in the middle of this region:
# -3 4 2 2 2
# -4 4 3 3 4
# -5 3 3 4 -4
# 4 3 3 4 -3
# 3 3 3 -5 -1
# What is the X,Y coordinate of the top-left fuel cell of the 3x3 square with the largest total power?
INPUT = File.read("day11.txt").to_i # 7139
find_power_level = ->(x,y) {
rack_id = x + 10
power_level = rack_id * y
power_level += INPUT
power_level *= rack_id
power_level = power_level.to_s[-3].to_i
power_level -= 5
power_level
}
grid = (1..300).to_a.map { |i|
(1..300).to_a.map { |j|
find_power_level.call(j, i)
}
}
answer = grid[0..-3].map.with_index { |row, grid_y|
# For each grid...
row[0..-3].map.with_index { |cell, grid_x|
# Calculate total power...
total = grid[grid_y, 3].map { |grid_row|
grid_row[grid_x, 3].sum
}.sum
[grid_x + 1, grid_y + 1, total]
}
}.flatten(1).sort_by(&:last).reverse[0, 10].first[0..1]
#puts "The answer to Part 1 is #{answer}" # 20,62
# --- Part Two ---
# You discover a dial on the side of the device; it seems to let you select a square of any size, not just 3x3. Sizes from 1x1 to 300x300 are supported.
# Realizing this, you now must find the square of any size with the largest total power. Identify this square by including its size as a third parameter after the top-left coordinate: a 9x9 square with a top-left corner of 3,5 is identified as 3,5,9.
# For example:
# For grid serial number 18, the largest total square (with a total power of 113) is 16x16 and has a top-left corner of 90,269, so its identifier is 90,269,16.
# For grid serial number 42, the largest total square (with a total power of 119) is 12x12 and has a top-left corner of 232,251, so its identifier is 232,251,12.
# What is the X,Y,size identifier of the square with the largest total power?
# Your puzzle input is still 7139.
grids = []
300.times { |i| powers[i] = }
grids = (1..300).to_a.map { |size|
print " #{size} " # progress
grid[0..-size].map.with_index { |row, grid_y|
# For each grid...
row[0..-size].map.with_index { |cell, grid_x|
# Calculate total power...
total = grid[grid_y, size].map { |grid_row|
grid_row[grid_x, size].sum
}.sum
[grid_x + 1, grid_y + 1, size, total]
}
}.flatten(1)
# NB This is a brute-force solution; I should've used a cached version each time (so grid 3 uses grid 2 + 1)
pp grids.sort_by(&:last).reverse[0, 10].first[0..2]
# The answer to Part 2 is 229, 61, 16
121212
evlewt
121212
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment