Advent of Code in Go: #3

1 minute read

In this series I explore the Advent of Code, or AoC for short, with the Go programming language. Every day, as real life permits, I will be solving a puzzle from the series. I will document each day with a solution in Go and a walkthrough of the code.

You can find the previous walkthroughs here.

The puzzle

This time the puzzle was about spiral memory. Given a spiral memory model we need to figure out the distance between the cell and the center point. This is called the Manhattan Distance.

The board will look like the following, spiraling out from 1, counter clockwise:

17  16  15  14  13
18   5   4   3  12
19   6   1   2  11
20   7   8   9  10
21  22  23---> ...

I basically calculated the root of the value, giving me the size of the grid (making sure it is uneven). Then take the centerpoint and calculate the number of cycles that need to occur. Then we can simply take the distance between the points.

func distance1(target int) int {
	if target == 1 {
		return 0
	root := int(math.Ceil(math.Sqrt(float64(target))))
	if root%2 == 0 {

	center := (root - 1) / 2
	cycle := target - int(math.Pow(float64(root-2), 2))

	innerOffset := cycle % (root - 1)

	return center + int(math.Abs(float64(innerOffset-center)))

The second part of the puzzle asked to calculate the value just greater then the cell index given that each cell, spiraling out, would become the sum of its neighbors. I was quite baffled to figure out a formula until I stumbled on the OEIS website which hosts known integer sequences. I then just looked up the value in the lookup table.

This puzzle is on my redo list as I feel I cheated it. So perhaps I will update this post with an actual programmed solution.

Tags: , ,