code.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type kind byte
  11. const (
  12. old kind = iota
  13. val
  14. )
  15. type variable struct {
  16. t kind
  17. val int
  18. }
  19. type operation struct {
  20. x variable
  21. y variable
  22. action byte
  23. }
  24. type monkey struct {
  25. items []int
  26. op operation
  27. }
  28. func readItems(line string) []int {
  29. line = strings.Replace(line, " Starting items: ", "", 1)
  30. parts := strings.Split(line, ", ")
  31. var result []int
  32. for i := range parts {
  33. n, err := strconv.Atoi(parts[i])
  34. if err != nil {
  35. log.Fatal("Can't pasrse", parts[i], err)
  36. }
  37. result = append(result, n)
  38. }
  39. return result
  40. }
  41. func readVariable(text string) variable {
  42. var result variable
  43. if text == "old" {
  44. result.t = old
  45. } else {
  46. result.t = val
  47. n, err := strconv.Atoi(text)
  48. if err != nil {
  49. log.Fatal("Can't pasrse", text, err)
  50. }
  51. result.val = n
  52. }
  53. return result
  54. }
  55. func readOperation(line string) operation {
  56. line = strings.Replace(line, " Operation: new = ", "", 1)
  57. parts := strings.Split(line, " ")
  58. if len(parts) != 3 {
  59. log.Fatal("Bad operation input:", line)
  60. }
  61. var result operation
  62. result.x = readVariable(parts[0])
  63. result.y = readVariable(parts[2])
  64. result.action = parts[1][0]
  65. return result
  66. }
  67. func readInput(file *os.File) []monkey {
  68. scanner := bufio.NewScanner(file)
  69. counter := 0
  70. var monkeys []monkey
  71. var currentMonkey monkey
  72. for scanner.Scan() {
  73. line := scanner.Text()
  74. if line == "" {
  75. monkeys = append(monkeys, currentMonkey)
  76. counter = 0
  77. currentMonkey = monkey{}
  78. continue
  79. }
  80. switch counter {
  81. case 1:
  82. currentMonkey.items = readItems(line)
  83. case 2:
  84. currentMonkey.op = readOperation(line)
  85. }
  86. counter++
  87. }
  88. monkeys = append(monkeys, currentMonkey)
  89. return monkeys
  90. }
  91. func main() {
  92. if len(os.Args) < 2 {
  93. log.Fatal("You need to specify a file!")
  94. }
  95. filePath := os.Args[1]
  96. file, err := os.Open(filePath)
  97. if err != nil {
  98. log.Fatalf("Failed to open %s!\n", filePath)
  99. }
  100. monkeys := readInput(file)
  101. fmt.Println(monkeys)
  102. }