63 lines
1.1 KiB
Go
63 lines
1.1 KiB
Go
package day01
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
"tools"
|
|
)
|
|
|
|
func getDistanceFromStart(instructions []string, breakOnRevisit bool) int {
|
|
x := 0
|
|
y := 0
|
|
z := 0
|
|
visited := tools.NewSet()
|
|
|
|
for _, instruction := range instructions {
|
|
switch instruction[0] {
|
|
case 'R':
|
|
z++
|
|
z = z % 4
|
|
case 'L':
|
|
z--
|
|
if z < 0 {
|
|
z += 4
|
|
}
|
|
}
|
|
distance, _ := strconv.Atoi(instruction[1:])
|
|
for i := 0; i < distance; i++ {
|
|
switch z {
|
|
case 0:
|
|
y--
|
|
case 1:
|
|
x++
|
|
case 2:
|
|
y++
|
|
case 3:
|
|
x--
|
|
}
|
|
|
|
if breakOnRevisit {
|
|
if visited.Contains(tools.Coordinate{X: x, Y: y}) {
|
|
return tools.Abs(x) + tools.Abs(y)
|
|
} else {
|
|
visited.Add(tools.Coordinate{X: x, Y: y})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return tools.Abs(x) + tools.Abs(y)
|
|
}
|
|
|
|
func Part1(puzzle tools.AoCPuzzle) interface{} {
|
|
instructions := puzzle.GetInputArray()
|
|
|
|
return getDistanceFromStart(strings.Split(instructions[0], ", "), false)
|
|
}
|
|
|
|
func Part2(puzzle tools.AoCPuzzle) interface{} {
|
|
instructions := puzzle.GetInputArray()
|
|
|
|
return getDistanceFromStart(strings.Split(instructions[0], ", "), true)
|
|
}
|