code.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "slices"
  8. )
  9. func readInput(file *os.File) ([]int, []int) {
  10. scanner := bufio.NewScanner(file)
  11. var lefts, rights []int
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. break
  16. }
  17. var left, right int
  18. n, err := fmt.Sscanf(line, "%d %d", &left, &right)
  19. if n != 2 || err != nil {
  20. log.Fatalf("Bad input: %s", line)
  21. }
  22. lefts = append(lefts, left)
  23. rights = append(rights, right)
  24. }
  25. return lefts, rights
  26. }
  27. func abs(a int) int {
  28. if a < 0 {
  29. return -a
  30. }
  31. return a
  32. }
  33. func part1(lefts, rights []int) int {
  34. slices.Sort(lefts)
  35. slices.Sort(rights)
  36. var distance int
  37. for i := range lefts {
  38. distance += abs(rights[i] - lefts[i])
  39. }
  40. return distance
  41. }
  42. func main() {
  43. if len(os.Args) < 2 {
  44. log.Fatal("You need to specify a file!")
  45. }
  46. filePath := os.Args[1]
  47. file, err := os.Open(filePath)
  48. if err != nil {
  49. log.Fatalf("Failed to open %s!\n", filePath)
  50. }
  51. lefts, rights := readInput(file)
  52. fmt.Println("Part1:", part1(lefts, rights))
  53. }