code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type Point struct {
  10. y, x int
  11. direction int
  12. }
  13. type Universe struct {
  14. galaxies []Point
  15. occupiedRows map[int]bool
  16. occupiedColumns map[int]bool
  17. }
  18. func readInput(file *os.File) Universe {
  19. scanner := bufio.NewScanner(file)
  20. var universe Universe
  21. universe.occupiedRows = make(map[int]bool)
  22. universe.occupiedColumns = make(map[int]bool)
  23. index := 0
  24. for scanner.Scan() {
  25. line := scanner.Text()
  26. if line == "" {
  27. break
  28. }
  29. if strings.Contains(line, "#") {
  30. universe.occupiedRows[index] = true
  31. for i := range line {
  32. if line[i] == '#' {
  33. universe.galaxies = append(universe.galaxies, Point{y: index, x: i})
  34. universe.occupiedColumns[i] = true
  35. }
  36. }
  37. }
  38. index++
  39. }
  40. return universe
  41. }
  42. func distances(universe Universe, multiple int) int {
  43. var result int
  44. edge := len(universe.galaxies)
  45. for i := range universe.galaxies {
  46. for j := i + 1; j < edge; j++ {
  47. distance := 0
  48. for y := universe.galaxies[i].y + 1; y <= universe.galaxies[j].y; y++ {
  49. if universe.occupiedRows[y] {
  50. distance++
  51. } else {
  52. distance += multiple
  53. }
  54. }
  55. start := universe.galaxies[i].x + 1
  56. end := universe.galaxies[j].x
  57. if start > end {
  58. start, end = end, start
  59. start++
  60. end--
  61. }
  62. for ; start <= end; start++ {
  63. if universe.occupiedColumns[start] {
  64. distance++
  65. } else {
  66. distance += multiple
  67. }
  68. }
  69. result += distance
  70. }
  71. }
  72. return result
  73. }
  74. func main() {
  75. if len(os.Args) < 2 {
  76. log.Fatal("You need to specify a file!")
  77. }
  78. filePath := os.Args[1]
  79. file, err := os.Open(filePath)
  80. if err != nil {
  81. log.Fatalf("Failed to open %s!\n", filePath)
  82. }
  83. universe := readInput(file)
  84. fmt.Println("Part1:", distances(universe, 2))
  85. fmt.Println("Part2:", distances(universe, 1000000))
  86. }