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 package main
import ( import (
"math"
"regexp" "regexp"
) )
@ -26,14 +25,5 @@ func one(lines []string) int {
imager := newImager() imager := newImager()
buildImage(fromRegex, imager, lines) buildImage(fromRegex, imager, lines)
area := 0 return calculateArea(imager.space)
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
} }

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"math"
"strings" "strings"
) )
@ -23,14 +22,5 @@ func two(lines []string) int {
imager := newImager() imager := newImager()
buildImage(fromHex, imager, lines) buildImage(fromHex, imager, lines)
area := 0 return calculateArea(imager.space)
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
} }

View File

@ -3,6 +3,7 @@ package main
import ( import (
"bufio" "bufio"
"log" "log"
"math"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
@ -47,7 +48,7 @@ func mustConv(s string) int {
return n return n
} }
// mustConv converts string to int // mustConvHex converts a hex string to int
// it will panic if an error occurs // it will panic if an error occurs
func mustConvHex(s string) int { func mustConvHex(s string) int {
n, err := strconv.ParseInt(s, 16, 64) n, err := strconv.ParseInt(s, 16, 64)
@ -56,3 +57,17 @@ func mustConvHex(s string) int {
} }
return int(n) 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
}