From 6d016405adc8330817af3f3d0b314c88211ad207 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Thu, 2 Dec 2021 19:34:17 +0000 Subject: [PATCH] day 2b complete --- day2/2b/go.mod | 3 +++ day2/2b/main.go | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 day2/2b/go.mod create mode 100644 day2/2b/main.go diff --git a/day2/2b/go.mod b/day2/2b/go.mod new file mode 100644 index 0000000..e938e2e --- /dev/null +++ b/day2/2b/go.mod @@ -0,0 +1,3 @@ +module PWD + +go 1.17 diff --git a/day2/2b/main.go b/day2/2b/main.go new file mode 100644 index 0000000..4b0f524 --- /dev/null +++ b/day2/2b/main.go @@ -0,0 +1,64 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +func main() { + content := returnContent("../input") + + horizontal, depth, _ := followGuidance(content) + + fmt.Println(horizontal * depth) + +} + +func returnContent(path string) *[]string { + //read file and return it as an array of integers + + file, err := os.Open(path) + var content []string + + if err != nil { + fmt.Println("Unlucky, the file didn't open") + return &content + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + content = append(content, scanner.Text()) + } + + return &content +} + +func followGuidance(content *[]string) (horizontal int, depth int, aim int) { + + for i := 0; i < len(*content); i++ { + currentLine := strings.Split((*content)[i], " ") + + value, err := strconv.Atoi(currentLine[1]) + + if err != nil { + fmt.Println("Uh oh, couldn't find the key! There was an issue with the sonar") + } + + switch currentLine[0] { + //instructions say that up and down are reversed as we are in the submarine + case "up": + aim -= value + case "down": + aim += value + default: + horizontal += value + depth += aim * value + } + } + return + +}