move area calculation into a function

fix mustConvHex docstring
This commit is contained in:
onyx-and-iris 2023-12-24 10:50:41 +00:00
parent 35776a5470
commit 73298dae8d
3 changed files with 18 additions and 23 deletions

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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
}