diff --git a/lib/day18.rb b/lib/day18.rb index 465e295..ee9bbc0 100644 --- a/lib/day18.rb +++ b/lib/day18.rb @@ -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] @@ -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 diff --git a/test/unit/day18_test.rb b/test/unit/day18_test.rb index 1c46cd0..c259cc1 100644 --- a/test/unit/day18_test.rb +++ b/test/unit/day18_test.rb @@ -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