Skip to content

Instantly share code, notes, and snippets.

@gurgeous
Created December 16, 2020 05:33
Show Gist options
  • Save gurgeous/9ceb70393345c2233b3923647d3095d6 to your computer and use it in GitHub Desktop.
Save gurgeous/9ceb70393345c2233b3923647d3095d6 to your computer and use it in GitHub Desktop.
#
# parse
#
rules, your, nearby = data.split("\n\n")
rules = rules.lines.map do |r|
r.scan(/(\d+)-(\d+)/).map { |x| Range.new(*x.map(&:to_i)) }
end
your = your.scan(/\d+/).map(&:to_i)
nearby = nearby.lines.map { |l| l.scan(/\d+/).map(&:to_i) }.select(&:present?)
#
# 1
#
answer = nearby.flatten.select { |v| rules.flatten.none? { |r| r === v } }.sum
p answer
#
# 2
#
# reject failures
nearby = nearby.reject do |tix|
tix.any? { |v| rules.flatten.none? { |r| r === v } }
end
# which columns match?
matches = rules.each.with_index.map do |rule, ri|
columns = nearby.first.each_index.select do |ii|
nearby.all? { |tix| rule.any? { |r| r === tix[ii] } }
end
[ ri, columns ]
end
# map[rule] => column
map = []
until matches.blank?
done, matches = matches.partition { |m| m[1].length == 1 }
done.each do |ri, cols|
map[ri] = cols.first
matches.each { |m| m[1].delete(cols.first) }
end
end
# done
answer = (0..5).map { |ri| your[map[ri]] }.inject(&:*)
p answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment