code.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "math"
  7. "os"
  8. "sort"
  9. )
  10. type box struct {
  11. x, y, z int
  12. id int
  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. func main() {
  40. if len(os.Args) < 2 {
  41. log.Fatal("You need to specify a file!")
  42. }
  43. filePath := os.Args[1]
  44. file, err := os.Open(filePath)
  45. if err != nil {
  46. log.Fatalf("Failed to open %s!\n", filePath)
  47. }
  48. markerBox := box{x: 0, y: 0, z: 0}
  49. boxes := readInput(file)
  50. fmt.Println(boxes[0], boxes[len(boxes)-1], boxes[0].DistanceTo(boxes[len(boxes)-1]))
  51. sort.Slice(boxes, func(i, j int) bool {
  52. return markerBox.DistanceTo(boxes[i]) < markerBox.DistanceTo(boxes[j])
  53. })
  54. for i := 1; i < len(boxes); i++ {
  55. fmt.Println(boxes[i], boxes[i-1], boxes[i].DistanceTo(boxes[i-1]))
  56. }
  57. }