2021 day6: 180/1133 too naive of an apparoach for part 1 got me a little crossed up:/

This commit is contained in:
alexchao26
2021-12-06 00:20:54 -05:00
parent f5e5d0b5f6
commit bfefeca827
2 changed files with 117 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
package main
import (
_ "embed"
"flag"
"fmt"
"strings"
"github.com/alexchao26/advent-of-code-go/cast"
"github.com/alexchao26/advent-of-code-go/util"
)
//go:embed input.txt
var input string
func init() {
// do this in init (not main) so test file has same input
input = strings.TrimRight(input, "\n")
if len(input) == 0 {
panic("empty input.txt file")
}
}
// 180/1133
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
ans := step(input, part)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
}
func step(input string, part int) int {
state := make([]int, 9)
for _, num := range strings.Split(input, ",") {
daysLeft := cast.ToInt(num)
state[daysLeft]++
}
// different number of days for part 1 vs part 2
days := 80
if part == 2 {
days = 256
}
// count down to zero
// then it makes a new lanternfish with a count of 8
for d := 0; d < days; d++ {
save := state[0]
for i := 0; i < len(state)-1; i++ {
state[i] = state[i+1]
}
state[8] = save
state[6] += save
}
// count up final sum
var sum int
for _, n := range state {
sum += n
}
return sum
}
+51
View File
@@ -0,0 +1,51 @@
package main
import (
"testing"
)
var example = `3,4,3,1,2`
func Test_part1(t *testing.T) {
tests := []struct {
name string
input string
part int
want int
}{
{
name: "example",
input: example,
part: 1,
want: 5934, // after 80 days
},
{
name: "actual",
input: input,
part: 1,
want: 362666,
},
{
name: "example",
input: example,
part: 2,
want: 26984457539,
},
{
name: "actual",
input: input,
part: 2,
want: 1640526601595,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.part == 0 {
t.Error("part value cannot be zero")
}
if got := step(tt.input, tt.part); got != tt.want {
t.Errorf("step() = %v, want %v", got, tt.want)
}
})
}
}