88 lines
1.4 KiB
Go
88 lines
1.4 KiB
Go
package two
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type command struct {
|
|
instruction string
|
|
value int
|
|
}
|
|
|
|
type sub struct {
|
|
input []command
|
|
depth int
|
|
horizontal int
|
|
aim int
|
|
}
|
|
|
|
// load Loads the commands from input.txt into the sub
|
|
func (s *sub) load(filename string) error {
|
|
s.input = []command{}
|
|
|
|
file, err := os.Open(filename)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
parts := strings.Split(scanner.Text(), " ")
|
|
if len(parts) != 2 {
|
|
return fmt.Errorf("Unable to parse input: %s", parts)
|
|
}
|
|
|
|
value, err := strconv.Atoi(parts[1])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.input = append(s.input, command{
|
|
instruction: parts[0],
|
|
value: value,
|
|
})
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *sub) reset() {
|
|
s.horizontal = 0
|
|
s.depth = 0
|
|
s.aim = 0
|
|
}
|
|
|
|
func (s *sub) execute() {
|
|
for _, command := range s.input {
|
|
switch command.instruction {
|
|
case "forward":
|
|
s.horizontal += command.value
|
|
case "up":
|
|
s.depth -= command.value
|
|
if s.depth < 0 {
|
|
s.depth = 0
|
|
}
|
|
case "down":
|
|
s.depth += command.value
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *sub) executeWithAim() {
|
|
for _, command := range s.input {
|
|
switch command.instruction {
|
|
case "forward":
|
|
s.horizontal += command.value
|
|
s.depth += s.aim * command.value
|
|
case "up":
|
|
s.aim -= command.value
|
|
case "down":
|
|
s.aim += command.value
|
|
}
|
|
}
|
|
}
|