Completed 7-1

This commit is contained in:
DutchEllie 2021-12-08 11:46:03 +01:00
parent 4b105b1a02
commit 1af11db2e6

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"math" "math"
"os" "os"
"sort"
"strconv" "strconv"
) )
@ -33,23 +34,46 @@ func main() {
} }
min, max := findMinMax(numbers) min, max := findMinMax(numbers)
leastFuel := max leastFuel := math.MaxInt
position := 0 position := 0
for i := min; i < max; i++ { for i := min; i < max; i++ {
fuel, _ := calculateFuel(numbers, i) fuel, _ := calculateFuel(numbers, i)
fmt.Printf("For position %d fuel costs %d\n", i, fuel)
if fuel < leastFuel { if fuel < leastFuel {
leastFuel = fuel leastFuel = fuel
position = i position = i
} }
} }
fmt.Printf("The least amount of fuel is: %d at position %d", leastFuel, position) // Calculating mean
total := 0.0
for i := 0; i < len(numbers); i++ {
total += float64(numbers[i])
}
mean := math.Round(total / float64(len(numbers)))
fmt.Printf("The average is: %f\n", mean)
// Calculating median
sort.Ints(numbers)
middle := len(numbers) / 2
median := 0.0
if middle%2 != 0 {
median = float64(numbers[middle])
} else {
median = float64((numbers[middle-1] + numbers[middle]) / 2)
}
fmt.Printf("The median is: %f\n", median)
fmt.Printf("The least amount of fuel is: %d at position %d\n", leastFuel, position)
} }
func calculateFuel(numbers []int, target int) (int, error) { func calculateFuel(numbers []int, target int) (int, error) {
fuel := 0 fuel := 0
for i := 0; i < len(numbers); i++ { for i := 0; i < len(numbers); i++ {
fuel += int(math.Abs(float64((numbers[i] - target)))) couldBeNegative := (numbers[i] - target)
if couldBeNegative < 0 {
couldBeNegative = couldBeNegative * -1
}
fuel += couldBeNegative
} }
return fuel, nil return fuel, nil
} }