diff --git a/06/input.txt b/06/input.txt new file mode 100644 index 0000000..89b026d --- /dev/null +++ b/06/input.txt @@ -0,0 +1 @@ +1,1,1,2,1,1,2,1,1,1,5,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,4,1,1,1,1,3,1,1,3,1,1,1,4,1,5,1,3,1,1,1,1,1,5,1,1,1,1,1,5,5,2,5,1,1,2,1,1,1,1,3,4,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,5,4,1,1,1,1,1,5,1,2,4,1,1,1,1,1,3,3,2,1,1,4,1,1,5,5,1,1,1,1,1,2,5,1,4,1,1,1,1,1,1,2,1,1,5,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,3,1,1,3,1,3,1,4,1,5,4,1,1,2,1,1,5,1,1,1,1,1,5,1,1,1,1,1,1,1,1,1,4,1,1,4,1,1,1,1,1,1,1,5,4,1,2,1,1,1,1,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,4,1,1,1,2,1,4,1,1,1,1,1,1,1,1,1,4,2,1,2,1,1,4,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,3,2,1,4,1,5,1,1,1,4,5,1,1,1,1,1,1,5,1,1,5,1,2,1,1,2,4,1,1,2,1,5,5,3 \ No newline at end of file diff --git a/06/main.go b/06/main.go new file mode 100644 index 0000000..629c143 --- /dev/null +++ b/06/main.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "log" + "os" + "strconv" + "strings" +) + +func main() { + inputBytes, _ := os.ReadFile("input.txt") + input := string(inputBytes) + + log.Println("Puzzle 1:", puzzle1(input)) + log.Println("Puzzle 2:", puzzle2(input)) +} + +func puzzle1(input string) int { + return do(input, 80) +} + +func puzzle2(input string) int { + return do(input, 256) +} + +func do(input string, days int) int { + var fish []int + total := 0 + // Parse initial state + for _, s := range strings.Split(input, ",") { + f, _ := strconv.Atoi(s) + fish = append(fish, f) + } + // Run simulation for each fish + for _, f := range fish { + total += countDescendants(f, days) + } + return total +} + +var cache = map[string]int{} + +func countDescendants(f int, days int) int { + if days == 0 || f-days >= 0 { + // Won't grow further + return 1 + } + // Check cache + if c, ok := cache[fmt.Sprintf("%d:%d", f, days)]; ok { + return c + } + result := 0 + if f == 0 { + // Add new fish + result = countDescendants(6, days-1) + countDescendants(8, days-1) + } else { + // Continue counting + result = countDescendants(f-1, days-1) + } + // Cache result + cache[fmt.Sprintf("%d:%d", f, days)] = result + return result +} diff --git a/06/main_test.go b/06/main_test.go new file mode 100644 index 0000000..34cf1bd --- /dev/null +++ b/06/main_test.go @@ -0,0 +1,16 @@ +package main + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test(t *testing.T) { + inputBytes, _ := os.ReadFile("test.txt") + input := string(inputBytes) + + assert.Equal(t, 5934, puzzle1(input)) + assert.Equal(t, 26984457539, puzzle2(input)) +} diff --git a/06/test.txt b/06/test.txt new file mode 100644 index 0000000..a7af2b1 --- /dev/null +++ b/06/test.txt @@ -0,0 +1 @@ +3,4,3,1,2 \ No newline at end of file