Updated day 6 code to be slightly smarter
This commit is contained in:
parent
819583bf06
commit
302185bbdf
1 changed files with 32 additions and 8 deletions
|
|
@ -56,7 +56,7 @@ func checkLoop(grid [][]string, initial, obstruction Location) bool {
|
||||||
|
|
||||||
direction := NORTH
|
direction := NORTH
|
||||||
loc := initial
|
loc := initial
|
||||||
for loc.X >= 0 && loc.X < len(grid[0]) && loc.Y >= 0 && loc.Y < len(grid) {
|
for true {
|
||||||
for _, dir := range visited[loc.Y][loc.X] {
|
for _, dir := range visited[loc.Y][loc.X] {
|
||||||
if dir == direction {
|
if dir == direction {
|
||||||
return true
|
return true
|
||||||
|
|
@ -89,11 +89,11 @@ func Part1(grid [][]string, initial Location) int {
|
||||||
|
|
||||||
direction := NORTH
|
direction := NORTH
|
||||||
loc := initial
|
loc := initial
|
||||||
for loc.X >= 0 && loc.X < len(grid[0]) && loc.Y >= 0 && loc.Y < len(grid) {
|
for true {
|
||||||
visited[loc.Y][loc.X] = true
|
visited[loc.Y][loc.X] = true
|
||||||
|
|
||||||
newLoc := transformations[direction](loc)
|
newLoc, status := applyTransform(loc, direction, grid)
|
||||||
if newLoc.X < 0 || newLoc.X >= len(grid[0]) || newLoc.Y < 0 || newLoc.Y >= len(grid) {
|
if !status {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -121,22 +121,46 @@ func Part2(grid [][]string, initial Location) int {
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
res := make(chan bool)
|
res := make(chan bool)
|
||||||
|
|
||||||
|
visited := make([][]bool, len(grid))
|
||||||
|
for i := range visited {
|
||||||
|
visited[i] = make([]bool, len(grid[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
direction := NORTH
|
||||||
|
loc := initial
|
||||||
|
for true {
|
||||||
|
visited[loc.Y][loc.X] = true
|
||||||
|
|
||||||
|
newLoc, status := applyTransform(loc, direction, grid)
|
||||||
|
if !status {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if grid[newLoc.Y][newLoc.X] == "#" {
|
||||||
|
newLoc = loc
|
||||||
|
direction = turnRight(direction)
|
||||||
|
}
|
||||||
|
|
||||||
|
loc = newLoc
|
||||||
|
}
|
||||||
|
|
||||||
for row := range grid {
|
for row := range grid {
|
||||||
for col := range grid[row] {
|
for col := range grid[row] {
|
||||||
|
if !visited[row][col] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
|
|
||||||
go func(row, col int) {
|
go func(row, col int) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
res <- checkLoop(grid, initial, Location{X: col, Y: row})
|
||||||
isLoop := checkLoop(grid, initial, Location{X: col, Y: row})
|
|
||||||
res <- isLoop
|
|
||||||
}(row, col)
|
}(row, col)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
defer close(res)
|
defer close(res)
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue