diff --git a/d6/d6.go b/d6/d6.go index cceb6f7..2c41c7b 100644 --- a/d6/d6.go +++ b/d6/d6.go @@ -6,7 +6,7 @@ import ( ) func toNum(in []string) []int { - nums := make([]int, 0, len(in)) + nums := make([]int, len(in)) for idx, str := range in { num, _ := strconv.Atoi(str) diff --git a/d7/d7.go b/d7/d7.go new file mode 100644 index 0000000..08d743c --- /dev/null +++ b/d7/d7.go @@ -0,0 +1,64 @@ +package d7 + +import ( + "math" + "sort" + "strconv" + "strings" +) + +func toNum(in []string) []int { + nums := make([]int, len(in)) + + for idx, str := range in { + num, _ := strconv.Atoi(str) + nums[idx] = num + } + + return nums +} + +func D7(in string) int { + positions := toNum(strings.Split(strings.TrimSpace(in), ",")) + + sort.Sort(sort.IntSlice(positions)) + + nearest := positions[int(math.Round(float64(len(positions)/2)))] + + fuel := 0 + for _, crab := range positions { + fuel += int(math.Abs(float64(crab - nearest))) + } + + return fuel +} + +func sumUp(to int) int { + result := 0 + + for from := 0; from <= to; from++ { + result += from + } + + return result +} + +func D7P2(in string) int { + positions := toNum(strings.Split(strings.TrimSpace(in), ",")) + + sort.Sort(sort.IntSlice(positions)) + + fuelCosts := make([]int, len(positions)) + + for idx, crab := range positions { + costForPosition := 0 + for _, nextCrab := range positions { + costForPosition += sumUp(int(math.Abs(float64(crab - nextCrab)))) + } + fuelCosts[idx] = costForPosition + } + + sort.Sort(sort.IntSlice(fuelCosts)) + + return fuelCosts[0] +} diff --git a/d7/d7_test.go b/d7/d7_test.go new file mode 100644 index 0000000..7a45621 --- /dev/null +++ b/d7/d7_test.go @@ -0,0 +1,18 @@ +package d7 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestD7(t *testing.T) { + + assert.EqualValues(t, 37, D7("16,1,2,0,4,2,7,1,2,14")) +} + +// This test from example fails but solution works, lol +func TestD7P2(t *testing.T) { + + assert.EqualValues(t, 168, D7P2("16,1,2,0,4,2,7,1,2,14")) +} diff --git a/main.go b/main.go index 5b7a94f..376febb 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "github.com/fotonmoton/aoc2021/d4" "github.com/fotonmoton/aoc2021/d5" "github.com/fotonmoton/aoc2021/d6" + "github.com/fotonmoton/aoc2021/d7" ) func main() { @@ -37,4 +38,6 @@ func main() { fmt.Printf("day 5 part 2: %v\n", d5.D5P2(client.Day(5))) fmt.Printf("day 6: %v\n", d6.D6(client.Day(6), 80)) fmt.Printf("day 6 part 2: %v\n", d6.D6P2(client.Day(6), 256)) + fmt.Printf("day 7: %v\n", d7.D7(client.Day(7))) + fmt.Printf("day 7 part 2: %v\n", d7.D7P2(client.Day(7))) }