This repository has been archived on 2021-12-06. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
adventofcode/pkg/two/two.go
T

71 lines
1.1 KiB
Go
Raw Normal View History

2021-12-02 12:47:13 +01:00
package two
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func Run() {
commands := readInput()
2021-12-06 10:24:09 +01:00
fmt.Printf("1st final position 🛰️: %d\n", solve(commands, false))
fmt.Printf("2nd final position 🛰️: %d\n", solve(commands, true))
2021-12-02 12:54:11 +01:00
}
2021-12-02 12:47:13 +01:00
2021-12-02 12:54:11 +01:00
func solve(commands []string, alt bool) int {
2021-12-02 15:36:10 +01:00
depth := 0
horizontalPosition := 0
aim := 0
2021-12-02 12:47:13 +01:00
for _, v := range commands {
2021-12-02 15:38:32 +01:00
2021-12-02 12:47:13 +01:00
command := strings.Split(v, " ")
2021-12-02 15:38:32 +01:00
x, err := strconv.Atoi(command[1])
if err != nil {
log.Fatal(err)
}
2021-12-02 12:47:13 +01:00
switch command[0] {
case "forward":
2021-12-02 13:22:34 +01:00
horizontalPosition += x
if alt {
depth += aim * x
}
2021-12-02 12:47:13 +01:00
case "up":
2021-12-02 13:22:34 +01:00
if !alt {
depth -= x
} else {
aim -= x
}
2021-12-02 12:47:13 +01:00
case "down":
2021-12-02 13:22:34 +01:00
if !alt {
depth += x
} else {
aim += x
}
2021-12-02 12:47:13 +01:00
}
}
2021-12-02 12:54:11 +01:00
return horizontalPosition * depth
2021-12-02 12:47:13 +01:00
}
func readInput() []string {
file, err := os.Open("./pkg/two/input.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
commands := make([]string, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
commands = append(commands, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return commands
}