You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.5 KiB
Go
51 lines
1.5 KiB
Go
package maths
|
|
|
|
import "math"
|
|
|
|
type Point struct {
|
|
X, Y float64
|
|
}
|
|
|
|
// ShoelaceArea calculates the area of a polygon using the Shoelace formula.
|
|
// It takes a slice of Point structs representing the vertices of the polygon.
|
|
// If the number of vertices is less than 3, it returns 0.0 indicating that it is not a valid polygon.
|
|
func ShoelaceArea(polygon []Point) float64 {
|
|
if len(polygon) < 3 {
|
|
return 0.0 // Not a polygon
|
|
}
|
|
|
|
var area float64 = 0.0
|
|
j := len(polygon) - 1 // The last vertex is the 'previous' one to the first
|
|
|
|
for i := 0; i < len(polygon); i++ {
|
|
area += (polygon[j].X + polygon[i].X) * (polygon[j].Y - polygon[i].Y)
|
|
j = i // j is previous vertex to i
|
|
}
|
|
|
|
return 0.5 * math.Abs(area)
|
|
}
|
|
|
|
// floodFill performs a flood fill algorithm on the given matrix starting from the specified row and column.
|
|
// It replaces all occurrences of the previous color with the new color.
|
|
// The height and width parameters define the dimensions of the matrix.
|
|
func floodFill(matrix Matrix[int64], row int, col int, prevColor int64, newColor int64, height int, width int) {
|
|
if row < 0 || row >= height || col < 0 || col >= width {
|
|
return
|
|
}
|
|
|
|
if matrix[row][col] != prevColor {
|
|
return
|
|
}
|
|
|
|
if matrix[row][col] == newColor {
|
|
return
|
|
}
|
|
|
|
matrix[row][col] = newColor
|
|
|
|
floodFill(matrix, row+1, col, prevColor, newColor, height, width)
|
|
floodFill(matrix, row-1, col, prevColor, newColor, height, width)
|
|
floodFill(matrix, row, col+1, prevColor, newColor, height, width)
|
|
floodFill(matrix, row, col-1, prevColor, newColor, height, width)
|
|
}
|