diff --git a/d2/d2.go b/d2/d2.go index e2849a6..47aa4e1 100644 --- a/d2/d2.go +++ b/d2/d2.go @@ -40,3 +40,36 @@ func D2(input string) int64 { return position.x * position.y } + +func D2P2(input string) int { + directions := strings.Split(strings.TrimSpace(input), "\n") + x := 0 + y := 0 + aim := 0 + + for _, direction := range directions { + directionAndValue := strings.Split(strings.TrimSpace(direction), " ") + + if len(directionAndValue) != 2 { + log.Fatal("line has wrong number of elements: ", direction) + } + + value, err := strconv.Atoi(directionAndValue[1]) + + if err != nil { + log.Fatal(err) + } + + switch directionAndValue[0] { + case "forward": + y += aim * value + x += value + case "down": + aim += value + case "up": + aim -= value + } + } + + return x * y +} diff --git a/d2/d2_test.go b/d2/d2_test.go index 2342fce..3564586 100644 --- a/d2/d2_test.go +++ b/d2/d2_test.go @@ -18,3 +18,16 @@ forward 2` assert.EqualValues(t, 150, D2(input)) } + +func TestD2P2(t *testing.T) { + + input := ` +forward 5 +down 5 +forward 8 +up 3 +down 8 +forward 2` + + assert.EqualValues(t, 900, D2P2(input)) +} diff --git a/main.go b/main.go index aaab4c2..a123941 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "github.com/fotonmoton/aoc2021/client" "github.com/fotonmoton/aoc2021/d1" "github.com/fotonmoton/aoc2021/d2" + "github.com/fotonmoton/aoc2021/d3" ) func main() { @@ -24,4 +25,7 @@ func main() { fmt.Printf("day 1: %v\n", d1.D1(client.Day(1))) fmt.Printf("day 1 part 2: %v\n", d1.D1P2(client.Day(1))) fmt.Printf("day 2: %v\n", d2.D2(client.Day(2))) + fmt.Printf("day 2 part 2: %v\n", d2.D2P2(client.Day(2))) + fmt.Printf("day 3: %v\n", d3.D3(client.Day(3))) + }