# Advent Of Code - Day 13

This one was a lot of fun! Matrix folding was a bit fiddly but nothing too serious…

## Day13 - Part 1

By solving this part, I actually solved both parts. I had to butcher it to not solve both parts because I already dealt with folding both ways. First, we parse our input.

We read out both the folding and the numbers first for easy handling later:

```
readingFolds := false
for _, line := range input {
// gather numbers
if line == "" {
readingFolds = true
continue
}
if !readingFolds {
numbers = append(numbers, line)
} else {
folders = append(folders, line)
}
}
```

Now, we have the numbers and folding bits in different slices. First, parse the numbers:

```
points := make([]point, 0)
maxx, maxy := 0, 0
for _, v := range numbers {
var (
x, y int
)
fmt.Sscanf(v, "%d,%d", &x, &y)
if x > maxx {
maxx = x
}
if y > maxy {
maxy = y
}
points = append(points, point{x: x, y: y})
}
```

Our trusty `Sscanf`

can help here again. Nice. We get the maximum length of things for later processing.

Then we parse the folding bits (I’m going to show “part 2” here, since that’s the same as part 1, just without a `for`

):

```
for _, f := range folders {
split := strings.Split(f, " ")
fold := split[len(split)-1]
if fold[0] == 'x' {
// fmt.Println("folding left")
var x int
fmt.Sscanf(fold, "x=%d", &x)
for y := 0; y < len(grid); y++ {
for j := x; j < len(grid[y]); j++ {
if grid[y][j] == "#" {
grid[y][x-(j-x)] = "#"
}
}
}
for i, v := range grid {
v = v[:x]
grid[i] = v
}
} else if fold[0] == 'y' {
// fmt.Println("folding up")
var y int
fmt.Sscanf(fold, "y=%d", &y)
// scan downwards
// offset is i - y 7-3 -> 4 and we subtract that from level (7)
for i := y; i < len(grid); i++ {
for x := 0; x < len(grid[i]); x++ {
if grid[i][x] == "#" {
grid[y-(i-y)][x] = "#"
}
}
}
grid = grid[:y]
}
}
```

This is a bit large and arguably, I could refactor this whole thing to be NOT this huge and separate. Let’s see what’s
happening here… First, Y, aka. fold up. We copy over all `#`

s to the other side. How
does the other side look like?

```
...#..#..#.
....#......
...........
#..........
...#....#.# -3
........... -2 (5)
........... -1 (6)
........... -- this is where it will fold -> this will be 0 -> 7
........... +1 (8)
........... +2 (9)
.#....#.##. +3
....#......
......#...#
#..........
#.#........
```

Then, we cut the grid at that point. Which is just `grid = grid[:y]`

in Go. Pretty neat.

And that’s it! For Part 2 I just added the loop and part 1 I just counter the `#`

s and we were done. On Part 2 I let it
fold and run a `display`

to see the points.

## Conclusion

Today we learned to count coordinates. I’m sure someone had a better way of calculating the outcome.

The repository for all my solutions for AOC 2021 can be found here.

Thank you for reading!

Gergely.