Skip to content

Commit 77cd82a

Browse files
committed
day 7 part 1 working on example data
1 parent 18a1833 commit 77cd82a

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

07/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/jamesjarvis/adventofcode/07
2+
3+
go 1.17

07/input.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
16,1,2,0,4,2,7,1,2,14

07/main.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package main
2+
3+
import (
4+
_ "embed"
5+
"fmt"
6+
"strconv"
7+
"strings"
8+
)
9+
10+
//go:embed input.txt
11+
var input string
12+
13+
var minPos, maxPos int
14+
15+
func main() {
16+
if input == "" {
17+
panic("input cannot be empty")
18+
}
19+
20+
inputstrarr := strings.Split(input, ",")
21+
world := &World{
22+
crabs: make([]int, 0, len(inputstrarr)),
23+
minPos: 1000000000,
24+
amountOfFuelRequired: 1000000000,
25+
}
26+
for _, val := range inputstrarr {
27+
n, err := strconv.Atoi(val)
28+
if err != nil {
29+
panic(err)
30+
}
31+
32+
if n < world.minPos {
33+
world.minPos = n
34+
}
35+
if n > world.maxPos {
36+
world.maxPos = n
37+
}
38+
world.crabs = append(world.crabs, n)
39+
}
40+
41+
idealFuelRequired := world.IdealFuelRequired()
42+
fmt.Printf("Answer: %d\n", idealFuelRequired)
43+
}
44+
45+
// Naive solution is to find the min and max values of the array, compute all fuel requirements for travelling
46+
// to all points between and choose the best one?
47+
48+
type World struct {
49+
minPos, maxPos int
50+
51+
crabs []int
52+
53+
idealPos int
54+
amountOfFuelRequired int
55+
}
56+
57+
func (w *World) IdealFuelRequired() (fuel int) {
58+
for pos := w.minPos; pos <= w.maxPos; pos++ {
59+
fuelRequired := w.FuelRequired(pos)
60+
if fuelRequired < w.amountOfFuelRequired {
61+
w.idealPos = pos
62+
w.amountOfFuelRequired = fuelRequired
63+
}
64+
}
65+
return w.amountOfFuelRequired
66+
}
67+
68+
func (w *World) FuelRequired(pos int) (fuel int) {
69+
for _, c := range w.crabs {
70+
if c < pos {
71+
fuel += (pos - c)
72+
} else {
73+
fuel += (c - pos)
74+
}
75+
}
76+
return fuel
77+
}

0 commit comments

Comments
 (0)