d02.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import "bufio"
  3. import "fmt"
  4. import "os"
  5. type Digicode struct {
  6. mat [][]string
  7. result string
  8. pos []int
  9. }
  10. func NewDigicode() Digicode {
  11. var res Digicode
  12. /** First case */
  13. /*
  14. res.pos = []int { 1, 1 }
  15. res.mat = append(res.mat, []string{"1", "2", "3"})
  16. res.mat = append(res.mat, []string{"4", "5", "6"})
  17. res.mat = append(res.mat, []string{"7", "8", "9"})
  18. */
  19. /** second case */
  20. res.pos = []int { 2, 0 }
  21. res.mat = append(res.mat, []string{".", ".", "1", ".", "."})
  22. res.mat = append(res.mat, []string{".", "2", "3", "4", "."})
  23. res.mat = append(res.mat, []string{"5", "6", "7", "8", "9"})
  24. res.mat = append(res.mat, []string{".", "A", "B", "C", "."})
  25. res.mat = append(res.mat, []string{".", ".", "D", ".", "."})
  26. return res
  27. }
  28. func (this *Digicode) NextDigit(line string) {
  29. code := make(map[rune][]int)
  30. code['U'] = []int { -1, 0 }
  31. code['D'] = []int { 1, 0 }
  32. code['L'] = []int { 0, -1 }
  33. code['R'] = []int { 0, 1 }
  34. for _, dir := range(line) {
  35. if (this.pos[0] + code[dir][0] < 0 ||
  36. this.pos[1] + code[dir][1] < 0 ||
  37. this.pos[0] + code[dir][0] >= len(this.mat) ||
  38. this.pos[1] + code[dir][1] >= len(this.mat[this.pos[0] + code[dir][0]])) {
  39. continue
  40. }
  41. newCode := []int { this.pos[0] + code[dir][0], this.pos[1] + code[dir][1]}
  42. if (this.mat[newCode[0]][newCode[1]] == ".") {
  43. continue
  44. }
  45. this.pos = newCode
  46. }
  47. this.result += this.mat[this.pos[0]][this.pos[1]]
  48. }
  49. func main() {
  50. reader := bufio.NewReader(os.Stdin)
  51. code := NewDigicode()
  52. for true {
  53. read, _, err := reader.ReadLine()
  54. if len(read) > 0 {
  55. code.NextDigit(string(read))
  56. }
  57. if (err != nil) {
  58. break
  59. }
  60. }
  61. fmt.Println("output: ", code.result)
  62. }