day 2b complete

This commit is contained in:
Luke Else 2021-12-02 19:34:17 +00:00
parent c0b80c74d2
commit 6d016405ad
2 changed files with 67 additions and 0 deletions

3
day2/2b/go.mod Normal file
View File

@ -0,0 +1,3 @@
module PWD
go 1.17

64
day2/2b/main.go Normal file
View File

@ -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
}