code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "math"
  7. "os"
  8. )
  9. type box struct {
  10. x, y, z int
  11. id, best int
  12. inCircuit bool
  13. }
  14. func (p box) DistanceTo(other box) float64 {
  15. dx := other.x - p.x
  16. dy := other.y - p.y
  17. dz := other.z - p.z
  18. return math.Sqrt(float64(dx*dx + dy*dy + dz*dz))
  19. }
  20. func readInput(file *os.File) []box {
  21. scanner := bufio.NewScanner(file)
  22. var boxes []box
  23. var id int
  24. for scanner.Scan() {
  25. line := scanner.Text()
  26. if line == "" {
  27. continue
  28. }
  29. var x, y, z int
  30. n, err := fmt.Sscanf(line, "%d,%d,%d", &x, &y, &z)
  31. if n != 3 || err != nil {
  32. log.Fatalf("Bad input: %s", line)
  33. }
  34. boxes = append(boxes, box{x: x, y: y, z: z, id: id})
  35. id++
  36. }
  37. return boxes
  38. }
  39. type circuit struct {
  40. first, second int
  41. boxes []box
  42. }
  43. func part1(boxes []box) int {
  44. var result int
  45. for i := range boxes {
  46. bestDistance := math.MaxFloat64
  47. best := -1
  48. for j := range boxes {
  49. if j == i {
  50. continue
  51. }
  52. distance := boxes[j].DistanceTo(boxes[i])
  53. if distance < bestDistance {
  54. bestDistance = distance
  55. best = j
  56. }
  57. }
  58. boxes[i].best = boxes[best].id
  59. }
  60. var circuits []circuit
  61. for _, item := range boxes {
  62. if item.inCircuit {
  63. continue
  64. }
  65. if boxes[item.best].best == item.id {
  66. item.inCircuit = true
  67. boxes[item.best].inCircuit = true
  68. set := circuit{first: item.id, second: item.best, boxes: []box{item, boxes[item.best]}}
  69. circuits = append(circuits, set)
  70. }
  71. }
  72. fmt.Println(circuits)
  73. return result
  74. }
  75. func main() {
  76. if len(os.Args) < 2 {
  77. log.Fatal("You need to specify a file!")
  78. }
  79. filePath := os.Args[1]
  80. file, err := os.Open(filePath)
  81. if err != nil {
  82. log.Fatalf("Failed to open %s!\n", filePath)
  83. }
  84. boxes := readInput(file)
  85. part1(boxes)
  86. }