~xenrox/aoc2021

c5a976fd9c7e40d70ad375a501dbf657a98979ab — Thorben Günther 2 years ago 5e5fc24
Solve day 2 part 2
2 files changed, 47 insertions(+), 0 deletions(-)

M day02/day02_test.go
M day02/main.go
M day02/day02_test.go => day02/day02_test.go +11 -0
@@ 12,3 12,14 @@ func Test1(t *testing.T) {
		t.Errorf("wrong result, expected %d, got %d", 150, res)
	}
}

func Test2(t *testing.T) {
	res, err := calc2("../data/day02_test.dat")
	if err != nil {
		t.Errorf("error calculating: %v", err)
	}

	if res != 900 {
		t.Errorf("wrong result, expected %d, got %d", 150, res)
	}
}

M day02/main.go => day02/main.go +36 -0
@@ 14,6 14,13 @@ func Run() {
	}

	fmt.Printf("Part 1: %d\n", res)

	res, err = calc2("data/day02.dat")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Part 2: %d\n", res)
}

func calc1(path string) (int, error) {


@@ 43,3 50,32 @@ func calc1(path string) (int, error) {

	return depth * hor, nil
}

func calc2(path string) (int, error) {
	lines, err := readFile(path)
	if err != nil {
		return 0, err
	}

	var hor, depth, aim int
	for i := 0; i < len(lines); i++ {
		v, err := strconv.Atoi(lines[i][1])
		if err != nil {
			return 0, err
		}

		switch lines[i][0] {
		case "forward":
			hor += v
			depth += aim * v
		case "down":
			aim += v
		case "up":
			aim -= v
		default:
			return 0, errors.New("illegal direction command")
		}
	}

	return depth * hor, nil
}