code.go 1.8 KB

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