code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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, circuit int
  12. }
  13. func (p box) DistanceTo(other box) float64 {
  14. dx := other.x - p.x
  15. dy := other.y - p.y
  16. dz := other.z - p.z
  17. return math.Sqrt(float64(dx*dx + dy*dy + dz*dz))
  18. }
  19. func readInput(file *os.File) []box {
  20. scanner := bufio.NewScanner(file)
  21. var boxes []box
  22. var id int
  23. for scanner.Scan() {
  24. line := scanner.Text()
  25. if line == "" {
  26. continue
  27. }
  28. var x, y, z int
  29. n, err := fmt.Sscanf(line, "%d,%d,%d", &x, &y, &z)
  30. if n != 3 || err != nil {
  31. log.Fatalf("Bad input: %s", line)
  32. }
  33. boxes = append(boxes, box{x: x, y: y, z: z, id: id})
  34. id++
  35. }
  36. return boxes
  37. }
  38. func part1(boxes []box) int {
  39. var result int
  40. circuit := 1
  41. for i := range boxes {
  42. bestDistance := math.MaxFloat64
  43. best := -1
  44. for j := range boxes {
  45. if j == i {
  46. continue
  47. }
  48. distance := boxes[j].DistanceTo(boxes[i])
  49. if distance < bestDistance {
  50. bestDistance = distance
  51. best = j
  52. }
  53. }
  54. if boxes[i].circuit > 0 {
  55. boxes[best].circuit = boxes[i].circuit
  56. } else if boxes[best].circuit > 0 {
  57. boxes[i].circuit = boxes[best].circuit
  58. } else {
  59. boxes[i].circuit = circuit
  60. boxes[best].circuit = circuit
  61. circuit++
  62. }
  63. }
  64. circuits := make([][]box, circuit)
  65. for i := range circuits {
  66. circuits[i] = []box{}
  67. }
  68. for _, box := range boxes {
  69. circuits[box.circuit] = append(circuits[box.circuit], box)
  70. }
  71. for _, circuit := range circuits {
  72. fmt.Println(circuit, len(circuit))
  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. boxes := readInput(file)
  86. part1(boxes)
  87. }