logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year git clone https://hacktivis.me/git/adventofcode.git

day2.go (1498B)


  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "math"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. func line_positions(line string) (positions [][2]int) {
  11. position := [2]int{0, 0} // (x,y)
  12. for _, move := range strings.Split(line, ",") {
  13. direction := strings.Split(move, "")[0]
  14. amount, err := strconv.Atoi(move[1:])
  15. if err != nil {
  16. fmt.Println(err)
  17. }
  18. for i := 0; i < amount; i++ {
  19. switch direction {
  20. case "U":
  21. position[0]++
  22. case "D":
  23. position[0]--
  24. case "L":
  25. position[1]++
  26. case "R":
  27. position[1]--
  28. }
  29. positions = append(positions, position)
  30. }
  31. }
  32. return
  33. }
  34. func main() {
  35. if len(os.Args) != 2 {
  36. fmt.Printf("Usage: %s [input file]\n", os.Args[0])
  37. os.Exit(1)
  38. }
  39. inputPath := os.Args[1]
  40. content, err := ioutil.ReadFile(inputPath)
  41. if err != nil {
  42. fmt.Println(err)
  43. os.Exit(1)
  44. }
  45. fileString := string(content)
  46. lines := strings.Split(fileString, "\n")
  47. line1 := line_positions(lines[0])
  48. line2 := line_positions(lines[1])
  49. var intercepts [][2]int
  50. for _, pos1 := range line1 {
  51. for _, pos2 := range line2 {
  52. if pos1 == pos2 {
  53. intercepts = append(intercepts, pos1)
  54. }
  55. }
  56. }
  57. fmt.Printf("%3d\n", intercepts)
  58. minDistance := float64(0)
  59. for _, intercept := range intercepts {
  60. var distance float64
  61. distance += math.Abs(float64(intercept[0]))
  62. distance += math.Abs(float64(intercept[1]))
  63. if minDistance == 0 {
  64. minDistance = distance
  65. } else {
  66. minDistance = math.Min(minDistance, distance)
  67. }
  68. }
  69. fmt.Println(minDistance)
  70. }