code.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type move struct {
  10. direction string
  11. steps int
  12. }
  13. func readInput(file string) []move {
  14. var moves []move
  15. content, err := ioutil.ReadFile(file)
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. lines := strings.Split(string(content), "\n")
  20. for _, line := range lines {
  21. if line == "" {
  22. continue
  23. }
  24. var currentMove move
  25. n, err := fmt.Sscanf(line, "%s %d", &currentMove.direction, &currentMove.steps)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. if n != 2 {
  30. continue
  31. }
  32. moves = append(moves, currentMove)
  33. }
  34. return moves
  35. }
  36. var actions map[string]int
  37. func init() {
  38. actions = make(map[string]int)
  39. actions["forward"] = 1
  40. actions["down"] = 1
  41. actions["up"] = -1
  42. }
  43. func part1(moves []move) int {
  44. position := 0
  45. depth := 0
  46. for _, move := range moves {
  47. if move.direction == "forward" {
  48. position += move.steps * actions[move.direction]
  49. } else {
  50. depth += move.steps * actions[move.direction]
  51. }
  52. }
  53. return position * depth
  54. }
  55. func part2(input []move) int {
  56. position := 0
  57. depth := 0
  58. aim := 0
  59. for _, move := range input {
  60. switch move.direction {
  61. case "forward":
  62. position += move.steps
  63. depth += aim * move.steps
  64. case "down":
  65. aim += move.steps
  66. case "up":
  67. aim -= move.steps
  68. }
  69. }
  70. return position * depth
  71. }
  72. func main() {
  73. if len(os.Args) < 2 {
  74. log.Fatal("No input file specified")
  75. }
  76. moves := readInput(os.Args[1])
  77. fmt.Println("Part 1:", part1(moves))
  78. fmt.Println("Part 2:", part2(moves))
  79. }