Browse Source

Brute forced, but solved part2

Piotr Czajkowski 2 weeks ago
parent
commit
6be0a1069a
1 changed files with 54 additions and 7 deletions
  1. 54 7
      06/code.go

+ 54 - 7
06/code.go

@@ -56,7 +56,7 @@ func readInput(file *os.File) (*Point, [][]byte) {
 	return guard, matrix
 }
 
-func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]bool) {
+func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int) {
 	if guard.x < 0 || guard.x > xMax || guard.y < 0 || guard.y > yMax {
 		return
 	}
@@ -66,7 +66,7 @@ func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]bool
 		guard.y -= directions[guard.direction][1]
 		guard.direction = (guard.direction + 1) % 4
 	} else {
-		visited[guard.key()] = true
+		visited[guard.key()]++
 		guard.x += directions[guard.direction][0]
 		guard.y += directions[guard.direction][1]
 	}
@@ -74,13 +74,58 @@ func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]bool
 	walk(guard, matrix, xMax, yMax, visited)
 }
 
-func part1(guard *Point, matrix [][]byte) int {
+func part1(guard *Point, matrix [][]byte) map[string]int {
 	xMax := len(matrix[0]) - 1
 	yMax := len(matrix) - 1
-	visited := make(map[string]bool)
+	visited := make(map[string]int)
 
-	walk(guard, matrix, xMax, yMax, visited)
-	return len(visited)
+	newGuard := Point{x: guard.x, y: guard.y}
+	walk(&newGuard, matrix, xMax, yMax, visited)
+	return visited
+}
+
+func walkWithCheck(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int) bool {
+	if guard.x < 0 || guard.x > xMax || guard.y < 0 || guard.y > yMax {
+		return true
+	}
+
+	if matrix[guard.y][guard.x] == '#' {
+		guard.x -= directions[guard.direction][0]
+		guard.y -= directions[guard.direction][1]
+		guard.direction = (guard.direction + 1) % 4
+	} else {
+		visited[guard.key()]++
+		if visited[guard.key()] > 4 {
+			return false
+		}
+
+		guard.x += directions[guard.direction][0]
+		guard.y += directions[guard.direction][1]
+	}
+
+	return walkWithCheck(guard, matrix, xMax, yMax, visited)
+}
+
+func part2(guard *Point, matrix [][]byte, expected map[string]int) int {
+	xMax := len(matrix[0]) - 1
+	yMax := len(matrix) - 1
+	var count int
+
+	for key, _ := range expected {
+		var x, y int
+		fmt.Sscanf(key, "%d_%d", &x, &y)
+		matrix[y][x] = '#'
+
+		visited := make(map[string]int)
+		newGuard := Point{x: guard.x, y: guard.y}
+		if !walkWithCheck(&newGuard, matrix, xMax, yMax, visited) {
+			count++
+		}
+
+		matrix[y][x] = '.'
+	}
+
+	return count
 }
 
 func main() {
@@ -95,5 +140,7 @@ func main() {
 	}
 
 	guard, matrix := readInput(file)
-	fmt.Println("Part1:", part1(guard, matrix))
+	visited := part1(guard, matrix)
+	fmt.Println("Part1:", len(visited))
+	fmt.Println("Part2:", part2(guard, matrix, visited))
 }