code.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. var directions [][]int = [][]int{
  9. {0, 1}, {1, 0}, {0, -1}, {-1, 0},
  10. }
  11. type Point struct {
  12. x, y int
  13. direction int
  14. }
  15. func (p *Point) key() string {
  16. return fmt.Sprintf("%d_%s", p.x, p.y)
  17. }
  18. func findGuard(line string) *Point {
  19. for i, char := range line {
  20. if char == '^' {
  21. return &Point{x: i}
  22. }
  23. }
  24. return nil
  25. }
  26. func readInput(file *os.File) (*Point, [][]byte) {
  27. scanner := bufio.NewScanner(file)
  28. var matrix [][]byte
  29. var guard *Point
  30. var y int
  31. for scanner.Scan() {
  32. line := scanner.Text()
  33. if line == "" {
  34. break
  35. }
  36. matrix = append(matrix, []byte(line))
  37. if guard == nil {
  38. guard = findGuard(line)
  39. if guard != nil {
  40. guard.y = y
  41. }
  42. }
  43. y++
  44. }
  45. return guard, matrix
  46. }
  47. func main() {
  48. if len(os.Args) < 2 {
  49. log.Fatal("You need to specify a file!")
  50. }
  51. filePath := os.Args[1]
  52. file, err := os.Open(filePath)
  53. if err != nil {
  54. log.Fatalf("Failed to open %s!\n", filePath)
  55. }
  56. guard, matrix := readInput(file)
  57. fmt.Println(guard, matrix)
  58. }