From 1b2cdbca69532f09f69fc118503c4493ee79a481 Mon Sep 17 00:00:00 2001 From: Gregory Date: Thu, 17 Feb 2022 01:25:23 +0200 Subject: [PATCH] d6 --- d6/d6.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++ d6/d6_test.go | 19 +++++++++++++++++ main.go | 3 +++ 3 files changed, 81 insertions(+) create mode 100644 d6/d6.go create mode 100644 d6/d6_test.go diff --git a/d6/d6.go b/d6/d6.go new file mode 100644 index 0000000..cceb6f7 --- /dev/null +++ b/d6/d6.go @@ -0,0 +1,59 @@ +package d6 + +import ( + "strconv" + "strings" +) + +func toNum(in []string) []int { + nums := make([]int, 0, len(in)) + + for idx, str := range in { + num, _ := strconv.Atoi(str) + nums[idx] = num + } + + return nums +} + +func D6(input string, startDays int) int { + fishes := toNum(strings.Split(strings.TrimSpace(input), ",")) + + for day := 0; day < startDays; day++ { + for idx := range fishes { + if fishes[idx] == 0 { + fishes[idx] = 6 + fishes = append(fishes, 8) + } else { + fishes[idx]-- + } + } + } + + return len(fishes) +} + +// Inspired by +// https://www.reddit.com/r/adventofcode/comments/r9z49j/comment/hnfaisu/?utm_source=share&utm_medium=web2x&context=3 +func D6P2(input string, startDays int) int { + fishes := toNum(strings.Split(strings.TrimSpace(input), ",")) + ages := make([]int, 9) + + for _, fish := range fishes { + ages[fish]++ + } + + for day := 0; day < startDays; day++ { + dieToday := ages[0] + ages = ages[1:] + ages[6] += dieToday + ages = append(ages, dieToday) + } + + sum := 0 + for _, age := range ages { + sum += age + } + + return sum +} diff --git a/d6/d6_test.go b/d6/d6_test.go new file mode 100644 index 0000000..e636cc2 --- /dev/null +++ b/d6/d6_test.go @@ -0,0 +1,19 @@ +package d6 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestD6(t *testing.T) { + assert.EqualValues(t, 5934, D6("3,4,3,1,2", 80)) +} + +func TestD6P2Naive(t *testing.T) { + assert.EqualValues(t, 26984457539, D6("3", 256)) +} + +func TestD6P2(t *testing.T) { + assert.EqualValues(t, 26984457539, D6P2("3,4,3,1,2", 256)) +} diff --git a/main.go b/main.go index 9eaf7a2..5b7a94f 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/fotonmoton/aoc2021/d3" "github.com/fotonmoton/aoc2021/d4" "github.com/fotonmoton/aoc2021/d5" + "github.com/fotonmoton/aoc2021/d6" ) func main() { @@ -34,4 +35,6 @@ func main() { fmt.Printf("day 4 part 2: %v\n", d4.D4P2(client.Day(4))) fmt.Printf("day 5: %v\n", d5.D5(client.Day(5))) 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)) }