1
0

solve day 4

This commit is contained in:
Rokas Puzonas 2024-12-05 22:07:42 +02:00
parent e715a03263
commit ee0ac427cf
2 changed files with 116 additions and 0 deletions

110
day4.go Normal file
View File

@ -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
}

View File

@ -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)
}
}
}