code.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. type point struct {
  21. x int
  22. y int
  23. }
  24. func howManyNeighbors(lines []string, x, y int) int {
  25. var count int
  26. for row := y - 1; row <= y+1; row++ {
  27. if row < 0 || row >= len(lines) {
  28. continue
  29. }
  30. for col := x - 1; col <= x+1; col++ {
  31. if col < 0 || col >= len(lines[row]) {
  32. continue
  33. }
  34. if row == y && col == x {
  35. continue
  36. }
  37. if lines[row][col] == '@' {
  38. count++
  39. }
  40. }
  41. }
  42. return count
  43. }
  44. func part1(lines []string) int {
  45. var count int
  46. for y := range lines {
  47. for x := range lines[y] {
  48. if lines[y][x] != '@' {
  49. continue
  50. }
  51. neighbors := howManyNeighbors(lines, x, y)
  52. if neighbors < 4 {
  53. count++
  54. }
  55. }
  56. }
  57. return count
  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. lines := readInput(file)
  69. fmt.Println("Part1:", part1(lines))
  70. }