Compare commits
No commits in common. "3e52a43f3c046a47ae4ad61d2192828e02f2493d" and "15a7b015d1467bcb77c0c7c99761b0e75218b692" have entirely different histories.
3e52a43f3c
...
15a7b015d1
95
2-1/main.go
95
2-1/main.go
@ -1,95 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
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))
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user