Add solution for day 3.
This commit is contained in:
parent
fd51b9dca2
commit
cf06140366
22
common.cr
Normal file
22
common.cr
Normal file
|
@ -0,0 +1,22 @@
|
|||
module Enumerable(T)
|
||||
def count_each(others)
|
||||
count_map = {} of T => Int32
|
||||
each do |other|
|
||||
count_map[other] = (count_map[other]? || 0) + 1
|
||||
end
|
||||
return count_map
|
||||
end
|
||||
end
|
||||
|
||||
class Rectangle
|
||||
def initialize(@x : Int32, @y : Int32, @width : Int32, @height : Int32)
|
||||
end
|
||||
|
||||
def each_coord(&block)
|
||||
(@x...(@x + @width)).each do |x|
|
||||
(@y...(@y + @height)).each do |y|
|
||||
yield x, y
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
38
day3.cr
Normal file
38
day3.cr
Normal file
|
@ -0,0 +1,38 @@
|
|||
require "./common.cr"
|
||||
|
||||
lines = File.read("day3").split("\n")
|
||||
lines.pop
|
||||
|
||||
REGEX = /#([0-9]+) @ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)/
|
||||
|
||||
claims = {} of Int32 => Rectangle
|
||||
lines.each do |line|
|
||||
match = line.match(REGEX).not_nil!
|
||||
claim = match[1].to_i32
|
||||
x = match[2].to_i32
|
||||
y = match[3].to_i32
|
||||
width = match[4].to_i32
|
||||
height = match[5].to_i32
|
||||
claims[claim] = Rectangle.new(x, y, width, height)
|
||||
end
|
||||
|
||||
claimed_coords = {} of Tuple(Int32, Int32) => Int32
|
||||
claims.values.each do |claim|
|
||||
claim.each_coord do |x, y|
|
||||
coord = {x, y}
|
||||
claimed_coords[coord] = (claimed_coords[coord]? || 0) + 1
|
||||
end
|
||||
end
|
||||
|
||||
puts "Overlapping: #{claimed_coords.values.count &.>(1)}"
|
||||
|
||||
claims.each do |k, v|
|
||||
count_overlapped = 0
|
||||
v.each_coord do |x, y|
|
||||
count_overlapped += 1 if claimed_coords[{x, y}] > 1
|
||||
end
|
||||
if count_overlapped == 0
|
||||
puts "No overlaps: #{k}"
|
||||
exit
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue
Block a user