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.2 KiB
Go
Raw Normal View History

2021-12-02 12:47:13 +01:00
package two
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
2021-12-02 12:54:11 +01:00
var depth int
var horizontalPosition int
var aim int
2021-12-02 12:47:13 +01:00
func Run() {
commands := readInput()
2021-12-02 12:54:11 +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:47:13 +01:00
2021-12-02 12:54:11 +01:00
func solve(commands []string, alt bool) int {
2021-12-02 12:47:13 +01:00
depth = 0
horizontalPosition = 0
2021-12-02 12:54:11 +01:00
aim = 0
2021-12-02 12:47:13 +01:00
for _, v := range commands {
command := strings.Split(v, " ")
switch command[0] {
case "forward":
2021-12-02 13:22:34 +01:00
x, _ := strconv.Atoi(command[1])
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
x, _ := strconv.Atoi(command[1])
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
x, _ := strconv.Atoi(command[1])
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
}