Completed 7-1

This commit is contained in:
DutchEllie 2021-12-08 11:46:03 +01:00
parent 4b105b1a02
commit 1af11db2e6
1 changed files with 27 additions and 3 deletions

View File

@ -6,6 +6,7 @@ import (
"fmt"
"math"
"os"
"sort"
"strconv"
)
@ -33,23 +34,46 @@ func main() {
}
min, max := findMinMax(numbers)
leastFuel := max
leastFuel := math.MaxInt
position := 0
for i := min; i < max; i++ {
fuel, _ := calculateFuel(numbers, i)
fmt.Printf("For position %d fuel costs %d\n", i, fuel)
if fuel < leastFuel {
leastFuel = fuel
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) {
fuel := 0
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
}