# Advent of Code in Go: #5

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

The CPU is in distress! It is stuck in a maze of registers and needs to figure out how many steps before it jumps out of the sequence. In a list of registers you jump the value of that register down the list. If the value is negative, you jump up. On each jump we increase the value of the register we jumped from. The sample explains each step:

``````(0) 3  0  1  -3  - before we have taken any steps.
(1) 3  0  1  -3  - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
2 (3) 0  1  -3  - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
2  4  0  1 (-3) - jump all the way to the end; leave a 4 behind.
2 (4) 0  1  -2  - go back to where we just were; increment -3 to -2.
2  5  0  1  -2  - jump 4 steps forward, escaping the maze.
``````

Again we use arrays to build our solution; using `append` to dynamically construct the sequence while converting the values to integers. It them just becomes a task of jumping on each step until the relative step becomes larger then the length of the sequence.

``````func escape(maze string) int {
fields := strings.Fields(maze)

m := []int{}

for _, v := range fields {
m = append(m, atoi(v))
}

index := 0
steps := 0

for {
jump := m[index]
m[index]++
steps++

if (index + jump) >= len(m) {
return steps
}
index = index + jump
}
}
``````

Out of the sequence the next maze question arrives. If the jump is larger then 2, then the value of the current index decreases instead. The rest of the logic remains the same.

``````func escape2(maze string) int {
fields := strings.Fields(maze)

m := []int{}

for _, v := range fields {
m = append(m, atoi(v))
}

index := 0
steps := 0

for {
jump := m[index]
if jump > 2 {
m[index]--
} else {
m[index]++
}
steps++

if (index + jump) >= len(m) {
return steps
}
index = index + jump
}
}
``````

I wonder if there is a better way to read the sequence of integers from the fileā¦.

Tags:

Updated: