2-1 completed
This commit is contained in:
parent
0922aa4437
commit
3e52a43f3c
92
2-1/main.go
92
2-1/main.go
@ -1,7 +1,95 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
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() {
|
func main() {
|
||||||
fmt.Println("Hello world!")
|
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