adventofcode2021/2-1/main.go

96 lines
1.5 KiB
Go
Raw Normal View History

2021-12-18 11:49:26 +01:00
package main
2021-12-18 12:15:38 +01:00
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Instruction struct {
instr int // forward = 0, up = 1, down = 2
value int
}
func (in *Instruction) execute(x, depth int) (int, int) {
switch in.instr {
case 0: // Forward
x += in.value
case 1: // Up
depth -= in.value
case 2: // Down
depth += in.value
}
return x, depth
}
func newInstruction(str string, val int) Instruction {
instr := 0
switch str {
case "forward":
instr = 0
case "up":
instr = 1
case "down":
instr = 2
}
in := Instruction{
instr: instr,
value: val,
}
return in
}
func parseInstruction(instruction string) (Instruction, error) {
instr := strings.Split(instruction, " ")
part1 := instr[0]
part2, err := strconv.Atoi(instr[1])
if err != nil {
return Instruction{}, err
}
return newInstruction(part1, part2), nil
}
func readInput(filename string) ([]Instruction, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
instructions := make([]Instruction, 0)
for scanner.Scan() {
in, err := parseInstruction(scanner.Text())
if err != nil {
return nil, err
}
instructions = append(instructions, in)
}
return instructions, nil
}
2021-12-18 11:49:26 +01:00
func main() {
2021-12-18 12:15:38 +01:00
ins, err := readInput("input")
if err != nil {
fmt.Printf("%s", err.Error())
return
}
xPos := 0
depth := 0
for i := 0; i < len(ins); i++ {
xPos, depth = ins[i].execute(xPos, depth)
}
fmt.Printf("X is now: %d\nDepth is now: %d\nMultiplied is: %d", xPos, depth, (xPos * depth))
2021-12-18 11:49:26 +01:00
}