code.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func readInput(file *os.File) []string {
  9. scanner := bufio.NewScanner(file)
  10. var lines []string
  11. for scanner.Scan() {
  12. line := scanner.Text()
  13. if line == "" {
  14. break
  15. }
  16. lines = append(lines, line)
  17. }
  18. return lines
  19. }
  20. const firstDigit = 48
  21. const lastDigit = 57
  22. func isDigit(b byte) bool {
  23. return firstDigit <= b && b <= lastDigit
  24. }
  25. func isSymbol(b byte) bool {
  26. return !isDigit(b) && b != '.'
  27. }
  28. func symbolNear(lines []string, height int, width int, y int, start int, end int) bool {
  29. i := start - 1
  30. if i < 0 {
  31. i = start
  32. }
  33. if end >= width {
  34. end = width - 1
  35. }
  36. canGoUp := y-1 >= 0
  37. canGoDown := y+1 < height
  38. for ; i <= end; i++ {
  39. if isSymbol(lines[y][i]) {
  40. return true
  41. }
  42. if canGoUp && isSymbol(lines[y-1][i]) {
  43. return true
  44. }
  45. if canGoDown && isSymbol(lines[y+1][i]) {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. func part1(lines []string) int {
  52. var result int
  53. height := len(lines)
  54. width := len(lines[0])
  55. edge := width - 1
  56. for i := range lines {
  57. var start, end int
  58. gotNumber := false
  59. tryRead := false
  60. for j := range lines[i] {
  61. if isDigit(lines[i][j]) {
  62. if !gotNumber {
  63. start = j
  64. gotNumber = true
  65. }
  66. if j == edge {
  67. end = j + 1
  68. tryRead = true
  69. }
  70. } else {
  71. if !gotNumber {
  72. continue
  73. }
  74. end = j
  75. gotNumber = false
  76. tryRead = true
  77. }
  78. if tryRead {
  79. if symbolNear(lines, height, width, i, start, end) {
  80. var d int
  81. n, err := fmt.Sscanf(lines[i][start:end], "%d", &d)
  82. if n != 1 || err != nil {
  83. log.Fatalf("Wrong input: %s\n%s", lines[i][start:end], err)
  84. }
  85. result += d
  86. }
  87. tryRead = false
  88. }
  89. }
  90. }
  91. return result
  92. }
  93. func main() {
  94. if len(os.Args) < 2 {
  95. log.Fatal("You need to specify a file!")
  96. }
  97. filePath := os.Args[1]
  98. file, err := os.Open(filePath)
  99. if err != nil {
  100. log.Fatalf("Failed to open %s!\n", filePath)
  101. }
  102. lines := readInput(file)
  103. fmt.Println("Part1:", part1(lines))
  104. }