Introduction
Moving on to day 4, we have a grid problem in front of us, we are given some numbers in the form of a grid, i.e. some rows and columns with some upper case letters. What we need to do is to find is the word XMAS in any direction (up, left, down, right, diagonals), and in the second part we need to find the word MAS forming an X.
So, let’s see how we can approach this and solve it in golang.
You can check out my solutions
Advent of Code
Constructing the grid
The most fundamental part of the problem lies in actually converting the text into a grid or a matrix form. We can split the lines, into individual lines and append each character as an element in a list, and that way we can have a list of list of strings which is a matrix or grid-like (2-dimensional) structure.
So, below is the input for the puzzle.
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
We need to convert it into something like this
[
[M M M S X X M A S M]
[M S A M X M S M S A]
[A M X S X M A A M M]
[M S A M A S M S M X]
[X M A S A M X A M M]
[X X A M M X X A M A]
[S M S M S A S X S S]
[S A X A M A S A A A]
[M A M M M X M M M M]
[M X M X A X M A S X]
]
So, this is a list of strings, we can say in golang it is a [][]string . We can do that by creating a function like this:
func ConstructGrid(lines []string) [][]string {
grid := [][]string{}
for _, line := range lines {
row := []string{}
for _, char := range strings.Split(line, "") {
row = append(row, char)
}
grid = append(grid, row)
}
return grid
}
The above function takes in a list of strings and returns a list of list of strings that are individual letters in the grid.
We can read the file bytes and split the bytes on newline characters and then this will be used as the input for this function.
So, once the input is parsed into a grid, we can start thinking about the actual logic of finding the word XMAS in it.
Part 1
So, in the first part, we need to find the word XMAS in the matrix which could be appearing:
forwards (as
XMAS)backward (as
SAMX)upwards
S
A
M
X
- downwards
X
M
A
S
- Diagonal upwards (right or up left)
S
A
M
X
OR
S
A
M
X
- Diagonals downwards (right or left)
X
M
A
S
OR
X
M
A
S
So, there are 8 directions where XMAS could appear in the grid, there could n number of these XMAS . We need to find the count of these in the grid.
Conclusion
So, that is it from day 4 of Advent of Code in Golang, let me know if you have any suggestions, and how you approached it. any better solutions?
Happy Coding :)
SOCIAL SHARE CARD GENERATOR