github.com/cycloss/advent-of-code@v0.0.0-20221210145555-15039b95faa6/2021/day2/day2.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 ) 8 9 func main() { 10 var file, err = os.Open("day2/day2.txt") 11 if err != nil { 12 fmt.Println(err) 13 } 14 defer file.Close() 15 solve(file) 16 } 17 18 func solve(file *os.File) { 19 var buff = bufio.NewScanner(file) 20 var x, y, y2 = 0, 0, 0 21 for buff.Scan() { 22 var line = buff.Text() 23 var instruction string 24 var num int 25 fmt.Sscanf(line, "%s %d", &instruction, &num) 26 handlePart1(instruction, num, &x, &y) 27 handlePart2(instruction, num, &y, &y2) 28 } 29 fmt.Printf("Forward: %d, Depth: %d\n", x, y) 30 fmt.Printf("Answer %d\n", x*y) 31 fmt.Printf("Part 2 Forward: %d, Depth: %d\n", x, y2) 32 fmt.Printf("Answer 2 %d\n", x*y2) 33 34 } 35 36 func handlePart1(instruction string, num int, x *int, y *int) { 37 switch instruction { 38 case "forward": 39 *x += num 40 case "down": 41 *y += num 42 case "up": 43 *y -= num 44 } 45 } 46 47 func handlePart2(instruction string, num int, aim *int, depth *int) { 48 if instruction == "forward" { 49 *depth += *aim * num 50 } 51 }