Advent of Code 2019 - Day 1

Posted on 2019-12-03

Advent of Code 2019 - Day 1

Background

Advent of Code is an awesome annual event where people around the world practice their programming chops by solving fun puzzles. I used last year’s AoC to learn JavaScript and I had a great experience (even though I didn’t finish!). This year I’m using AoC as an opportunity to learn Go!

I’m working through Learn Go with Tests to learn the concepts and applying them by solving AoC’s daily puzzle. So if you see some solution where it would be way better to use something else, it’s possible that I haven’t gotten there yet. It’s also possible that I just didn’t think of it! Either way, feel free to point it out to me on Twitter.

You can find my solutions repo here.

Solution

The fuel calculation is straightforward enough. The most challenging part for me was simply figuring out how to read files with Go. This is the pattern I settled on, it seems fine (as long as my assumptions about the input data hold - famous last words).

func day1Puzzle1() (sum int) {
	f, err := os.Open("./input/day1.txt")
	check(err)

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		val, err := strconv.Atoi(scanner.Text())
		check(err)
		sum += calcModuleFuel(val)
	}

	return sum
}

Throughout all of the puzzles, my input handling code isn’t going to focus on potential edge cases like you would in production software. This would be more important if we had to run the code using black box input like HackerRank.

The second part is also pretty simple to solve if you broke out the calculation into a function - you can just recursively call calcModuleFuel on the additional fuel required until it hits zero.

func calcModuleFuel(mass int) (fuel int) {
	fuel = (mass / 3) - 2
	if fuel <= 0 {
		fuel = 0
	}
	return
}

func calcTotalModuleFuel(mass int) (fuel int) {
	nextFuel := calcModuleFuel(mass)

	for nextFuel > 0 {
		fuel += nextFuel
		nextFuel = calcModuleFuel(nextFuel)
	}

	return
}

This was a nice puzzle to get the ball rolling and it helped me smooth out the Go file I/O thing early. Looking forward to the additional puzzles.

You can find my solution repo here.