-
Notifications
You must be signed in to change notification settings - Fork 0
/
day07.go
86 lines (75 loc) · 1.78 KB
/
day07.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"github.com/dergeberl/aoc/utils"
"os"
"strconv"
"strings"
)
type crabs []int
func main() {
input, err := os.ReadFile("input.txt")
if err != nil {
os.Exit(1)
}
fmt.Printf("Part 1: %v\n", SolveDay07Part1(string(input)))
fmt.Printf("Part 2: %v\n", SolveDay07Part2(string(input)))
}
//SolveDay07Part1 returns the sum of fuel for all submarines on the optimal position
func SolveDay07Part1(input string) int {
c := getNumbersFromList(input)
return c.getSumOfNeededFuel(false)
}
//SolveDay07Part2 returns the sum of fuel for all submarines on the optimal position
func SolveDay07Part2(input string) int {
c := getNumbersFromList(input)
return c.getSumOfNeededFuel(true)
}
// getSumOfNeededFuel returns the sum of fuel for all submarines on the optimal position
func (c crabs) getSumOfNeededFuel(crabVersion bool) int {
l, h := c.getRange()
fuel := len(c) * utils.GetGaussscheSummenformel(utils.GetDiff(l, h))
for i := l; i <= h; i++ {
tmpFuel := 0
for cr := range c {
if crabVersion {
tmpFuel += utils.GetGaussscheSummenformel(utils.GetDiff(i, c[cr]))
continue
}
tmpFuel += utils.GetDiff(i, c[cr])
}
if tmpFuel < fuel {
fuel = tmpFuel
}
if tmpFuel > fuel {
break
}
}
return fuel
}
// getRange returns the lowest and highest position of the crab submarines
func (c crabs) getRange() (int, int) {
var height, low int
for i := range c {
if height < i {
height = i
}
}
low = height
for i := range c {
if low > i {
low = i
}
}
return low, height
}
// getNumbersFromList returns the crab submarines
func getNumbersFromList(input string) crabs {
numbers := strings.Split(input, ",")
var output []int
for i := range numbers {
tmpInt, _ := strconv.Atoi(numbers[i])
output = append(output, tmpInt)
}
return output
}