Skip to content

Commit

Permalink
chore: solution for day18b
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaxwood committed Dec 18, 2023
1 parent e949a55 commit 6615a79
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
44 changes: 44 additions & 0 deletions lib/day18.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ def fill(dig)
end
end

# area of a polygon
def area(coordinates)
n = coordinates.length
area = 0
perimeter = 0

(0..n - 1).each do |i|
x1, y1 = coordinates[i]
x2, y2 = coordinates[(i + 1) % n]

area += (x1 * y2 - x2 * y1)
perimeter += Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
end

area = area.abs / 2.0
(area + (perimeter / 2.0) + 1).to_i
end

def part1
dig = {}
cursor = [0, 0]
Expand Down Expand Up @@ -58,4 +76,30 @@ def part1
fill(dig)
dig.keys.count
end

def part2
coords = [[0, 0]]
@lines.each do |line|
segments = line.split(' ')
size = segments[2][2..-3].hex.to_i
direction = segments[2][2..-2][-1].to_i
coords << case direction
when 0 # right
cursor = coords[-1]
[cursor[0] + size, cursor[1]]
when 1 # down
cursor = coords[-1]
[cursor[0], cursor[1] + size]
when 2 # left
cursor = coords[-1]
[cursor[0] - size, cursor[1]]
when 3 # up
cursor = coords[-1]
[cursor[0], cursor[1] - size]
else
raise "Unknown direction #{direction}"
end
end
area(coords)
end
end
12 changes: 12 additions & 0 deletions test/unit/day18_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,21 @@ def test_day18a
assert_equal(62, sut.part1)
end

def test_day18b
sut = Day18.new
sut.load('data/day18a.txt')
assert_equal(952_408_144_115, sut.part2)
end

def test_day18_part1
sut = Day18.new
sut.load('data/day18.txt')
assert_equal(40_745, sut.part1)
end

def test_day18_part2
sut = Day18.new
sut.load('data/day18.txt')
assert_equal(90_111_113_594_927, sut.part2)
end
end

0 comments on commit 6615a79

Please sign in to comment.