diff --git a/day4.go b/day4.go new file mode 100644 index 0000000..d94d361 --- /dev/null +++ b/day4.go @@ -0,0 +1,110 @@ +package main + +type Day4Offset struct { + x int + y int +} + +func Day4IsWordValid(lines []string, x int, y int, table []Day4Offset, word string) bool { + for i, offset := range table { + y := y + offset.y + if y < 0 { + return false + } + if y >= len(lines) { + return false + } + + x := x + offset.x + if x < 0 { + return false + } + if x >= len(lines[y]) { + return false + } + + if lines[y][x] != word[i] { + return false + } + } + + return true +} + +func Day4Part1(lines []string) error { + offsetTables := [][]Day4Offset{ + []Day4Offset{ + Day4Offset{ x: 0, y: 0, }, + Day4Offset{ x: 1, y: 0, }, + Day4Offset{ x: 2, y: 0, }, + Day4Offset{ x: 3, y: 0, }, + }, + []Day4Offset{ + Day4Offset{ x: 0, y: 0, }, + Day4Offset{ x: 0, y: 1, }, + Day4Offset{ x: 0, y: 2, }, + Day4Offset{ x: 0, y: 3, }, + }, + []Day4Offset{ + Day4Offset{ x: 0, y: 0, }, + Day4Offset{ x: 1, y: 1, }, + Day4Offset{ x: 2, y: 2, }, + Day4Offset{ x: 3, y: 3, }, + }, + []Day4Offset{ + Day4Offset{ x: 0, y: 0, }, + Day4Offset{ x: -1, y: 1, }, + Day4Offset{ x: -2, y: 2, }, + Day4Offset{ x: -3, y: 3, }, + }, + } + + answer := 0 + for y := range len(lines) { + for x := range len(lines[y]) { + for _, table := range offsetTables { + if Day4IsWordValid(lines, x, y, table, "XMAS") { + answer += 1 + } + + if Day4IsWordValid(lines, x, y, table, "SAMX") { + answer += 1 + } + } + } + } + + println(answer) + + return nil +} + +func Day4Part2(lines []string) error { + table1 := []Day4Offset{ + Day4Offset{ x: 0, y: 0, }, + Day4Offset{ x: 1, y: 1, }, + Day4Offset{ x: 2, y: 2, }, + } + + table2 := []Day4Offset{ + Day4Offset{ x: 2, y: 0, }, + Day4Offset{ x: 1, y: 1, }, + Day4Offset{ x: 0, y: 2, }, + } + + answer := 0 + for y := range len(lines) { + for x := range len(lines[y]) { + diagonal1 := Day4IsWordValid(lines, x, y, table1, "MAS") || Day4IsWordValid(lines, x, y, table1, "SAM") + diagonal2 := Day4IsWordValid(lines, x, y, table2, "MAS") || Day4IsWordValid(lines, x, y, table2, "SAM") + + if diagonal1 && diagonal2 { + answer += 1 + } + } + } + + println(answer) + + return nil +} diff --git a/main.go b/main.go index ca2d31b..ae5502a 100644 --- a/main.go +++ b/main.go @@ -53,5 +53,11 @@ func main() { } else if part == "2" { Day3Part2(lines) } + } else if day == "4" { + if part == "1" { + Day4Part1(lines) + } else if part == "2" { + Day4Part2(lines) + } } }