Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Created December 16, 2020 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeRogers0/06c169a1dafaaa3e5541d2a990bb009d to your computer and use it in GitHub Desktop.
Save MikeRogers0/06c169a1dafaaa3e5541d2a990bb009d to your computer and use it in GitHub Desktop.
Advent Of Code - Day 16: Part 2
@section = File.open('input.real.txt').read.split("\n\n").compact
# Get all the rules as ranges (e.g. 0..3), with their names.
@rules = @section[0]
.split("\n")
.collect { |line|
line.scan(/(.+): ([0-9\-]+)-([0-9]+) or ([0-9\-]+)-([0-9]+)/ism).flatten
}
.collect { |name, start_range_1, end_range_1, start_range_2, end_range_2|
{
name: name,
ranges: [
(start_range_1.to_i..end_range_1.to_i),
(start_range_2.to_i..end_range_2.to_i),
],
index: []
}
}
# Load my ticket numbers
@my_ticket = @section[1]
.gsub("your ticket:\n", '')
.split("\n")
.compact
.collect { |ticket| ticket.split(',').collect(&:to_i) }.first
# Load nearby ticket numbers
@nearby_tickets = @section[2]
.gsub("nearby tickets:\n", '')
.split("\n")
.compact
.collect { |ticket| ticket.split(',').collect(&:to_i) }
# Remove all the tickets that are invalid for any rules
@nearby_tickets.select! do |ticket|
ticket.all? do |ticket_number|
@rules.any? do |rule|
rule[:ranges].any? { |range| range.cover?(ticket_number) }
end
end
end
def find_potential_indexes_for_rules(index)
@rules.each_with_index do |rule, rule_index|
if @nearby_tickets.all? { |ticket| rule[:ranges].any? { |range| range.cover?(ticket[index]) } }
rule[:index] << index
end
end
end
# Identify which column is valid for each rules
@nearby_tickets[0].each_with_index do |_number, index|
find_potential_indexes_for_rules(index)
end
# Keep reducing the potential indexes, until each rule only has one index left
while(@rules.collect { |rule| rule[:index] }.compact.flatten.length > @rules.length) do
@found_indexes = @rules
.select{ |rule| rule[:index].length == 1 }
.collect { |rule| rule[:index] }.flatten
@rules.each do |rule|
next if rule[:index].length == 1
rule[:index] -= @found_indexes
end
end
@indexes_for_deperatures = @rules
.select { |rule| rule[:name].start_with?("departure") }
.collect { |rule| rule[:index] }
.flatten
@numbers_on_my_ticket_for_deperatures = @indexes_for_deperatures.collect do |index|
@my_ticket[index]
end
puts @numbers_on_my_ticket_for_deperatures.inspect
puts @numbers_on_my_ticket_for_deperatures.inject(&:*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment