move to lib
This commit is contained in:
@@ -24,15 +24,11 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"scm.dairydemon.net/filifa/mathtools/internal/lib"
|
||||
)
|
||||
|
||||
var shoelaceFile string
|
||||
|
||||
type point struct {
|
||||
x float64
|
||||
y float64
|
||||
}
|
||||
|
||||
func splitLines(file *os.File) []string {
|
||||
slice := make([]string, 0)
|
||||
scanner := bufio.NewScanner(file)
|
||||
@@ -43,8 +39,8 @@ func splitLines(file *os.File) []string {
|
||||
return slice
|
||||
}
|
||||
|
||||
func readFromFile(filepath string) ([]point, error) {
|
||||
points := make([]point, 0)
|
||||
func readFromFile(filepath string) ([]lib.Point, error) {
|
||||
points := make([]lib.Point, 0)
|
||||
file, err := os.Open(filepath)
|
||||
if err != nil {
|
||||
return points, err
|
||||
@@ -65,25 +61,14 @@ func readFromFile(filepath string) ([]point, error) {
|
||||
return points, err
|
||||
}
|
||||
|
||||
points = append(points, point{x, y})
|
||||
points = append(points, lib.Point{x, y})
|
||||
}
|
||||
|
||||
return points, nil
|
||||
}
|
||||
|
||||
func area(points []point) float64 {
|
||||
total := float64(0)
|
||||
n := len(points)
|
||||
for i, p := range points {
|
||||
q := points[(i+1)%n]
|
||||
total += (p.y + q.y) * (p.x - q.x)
|
||||
}
|
||||
|
||||
return total / 2
|
||||
}
|
||||
|
||||
func shoelace(cmd *cobra.Command, args []string) {
|
||||
var coordinates []point
|
||||
var coordinates []lib.Point
|
||||
var err error
|
||||
if shoelaceFile != "" {
|
||||
coordinates, err = readFromFile(shoelaceFile)
|
||||
@@ -94,7 +79,7 @@ func shoelace(cmd *cobra.Command, args []string) {
|
||||
cobra.CheckErr("filename required")
|
||||
}
|
||||
|
||||
fmt.Println(area(coordinates))
|
||||
fmt.Println(lib.Area(coordinates))
|
||||
}
|
||||
|
||||
// shoelaceCmd represents the shoelace command
|
||||
|
||||
Reference in New Issue
Block a user