Reading numbers
This commit is contained in:
parent
9d94781dae
commit
4b105b1a02
37
7-1/main.go
37
7-1/main.go
@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
@ -15,6 +16,42 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
// Alright, I am going for the simplest and most (reasonably) computationally expensive solution
|
||||
// So like... Don't hate on me for this XD
|
||||
findMinMax := func(slice []int) (min int, max int) {
|
||||
min = slice[0]
|
||||
max = slice[0]
|
||||
for _, value := range slice {
|
||||
if value < min {
|
||||
min = value
|
||||
}
|
||||
if value > max {
|
||||
max = value
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
min, max := findMinMax(numbers)
|
||||
leastFuel := max
|
||||
position := 0
|
||||
for i := min; i < max; i++ {
|
||||
fuel, _ := calculateFuel(numbers, i)
|
||||
if fuel < leastFuel {
|
||||
leastFuel = fuel
|
||||
position = i
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("The least amount of fuel is: %d at position %d", 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))))
|
||||
}
|
||||
return fuel, nil
|
||||
}
|
||||
|
||||
func readInput(inputfile string) ([]int, error) {
|
||||
|
Loading…
Reference in New Issue
Block a user