From 73298dae8d4d46c06aab0aec00af9f1d406a2ac2 Mon Sep 17 00:00:00 2001 From: onyx-and-iris Date: Sun, 24 Dec 2023 10:50:41 +0000 Subject: [PATCH] move area calculation into a function fix mustConvHex docstring --- day-18/one.go | 12 +----------- day-18/two.go | 12 +----------- day-18/util.go | 17 ++++++++++++++++- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/day-18/one.go b/day-18/one.go index 19a1b79..b826bec 100644 --- a/day-18/one.go +++ b/day-18/one.go @@ -1,7 +1,6 @@ package main import ( - "math" "regexp" ) @@ -26,14 +25,5 @@ func one(lines []string) int { imager := newImager() buildImage(fromRegex, imager, lines) - area := 0 - for i := 0; i < len(imager.space); i++ { - next := imager.space[(i+1)%len(imager.space)] - area += imager.space[i].X*next.Y - imager.space[i].Y*next.X - } - - // add perimeter to area within perimeter - area = len(imager.space) + (int(math.Abs(float64(area))) / 2) - - return area - len(imager.space)/2 + 1 + return calculateArea(imager.space) } diff --git a/day-18/two.go b/day-18/two.go index 0b68418..b22869d 100644 --- a/day-18/two.go +++ b/day-18/two.go @@ -1,7 +1,6 @@ package main import ( - "math" "strings" ) @@ -23,14 +22,5 @@ func two(lines []string) int { imager := newImager() buildImage(fromHex, imager, lines) - area := 0 - for i := 0; i < len(imager.space); i++ { - next := imager.space[(i+1)%len(imager.space)] - area += imager.space[i].X*next.Y - imager.space[i].Y*next.X - } - - // add perimeter to area within perimeter - area = len(imager.space) + (int(math.Abs(float64(area))) / 2) - - return area - len(imager.space)/2 + 1 + return calculateArea(imager.space) } diff --git a/day-18/util.go b/day-18/util.go index 09ad1c6..7391a99 100644 --- a/day-18/util.go +++ b/day-18/util.go @@ -3,6 +3,7 @@ package main import ( "bufio" "log" + "math" "os" "regexp" "strconv" @@ -47,7 +48,7 @@ func mustConv(s string) int { return n } -// mustConv converts string to int +// mustConvHex converts a hex string to int // it will panic if an error occurs func mustConvHex(s string) int { n, err := strconv.ParseInt(s, 16, 64) @@ -56,3 +57,17 @@ func mustConvHex(s string) int { } return int(n) } + +// calculateArea returns the area of the polygon described by imager.space +func calculateArea(space []coords) int { + area := 0 + for i := 0; i < len(space); i++ { + next := space[(i+1)%len(space)] + area += space[i].X*next.Y - space[i].Y*next.X + } + + // add perimeter to area within perimeter + area = len(space) + (int(math.Abs(float64(area))) / 2) + + return area - len(space)/2 + 1 +}