code.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 part2(lefts, rights []int) int {
  43. onTheLeft := make(map[int]int)
  44. for _, left := range lefts {
  45. onTheLeft[left] = 0
  46. }
  47. for _, right := range rights {
  48. _, ok := onTheLeft[right]
  49. if ok {
  50. onTheLeft[right]++
  51. }
  52. }
  53. var result int
  54. for _, left := range lefts {
  55. result += left * onTheLeft[left]
  56. }
  57. return result
  58. }
  59. func main() {
  60. if len(os.Args) < 2 {
  61. log.Fatal("You need to specify a file!")
  62. }
  63. filePath := os.Args[1]
  64. file, err := os.Open(filePath)
  65. if err != nil {
  66. log.Fatalf("Failed to open %s!\n", filePath)
  67. }
  68. lefts, rights := readInput(file)
  69. fmt.Println("Part1:", part1(lefts, rights))
  70. fmt.Println("Part2:", part2(lefts, rights))
  71. }