code.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type monkey struct {
  11. items []int
  12. }
  13. func readItems(line string) []int {
  14. line = strings.Replace(line, " Starting items: ", "", 1)
  15. parts := strings.Split(line, ", ")
  16. var result []int
  17. for i := range parts {
  18. n, err := strconv.Atoi(parts[i])
  19. if err != nil {
  20. log.Fatal("Can't pasrse", parts[i], err)
  21. }
  22. result = append(result, n)
  23. }
  24. return result
  25. }
  26. func readInput(file *os.File) []monkey {
  27. scanner := bufio.NewScanner(file)
  28. counter := 0
  29. var monkeys []monkey
  30. var currentMonkey monkey
  31. for scanner.Scan() {
  32. line := scanner.Text()
  33. if line == "" {
  34. monkeys = append(monkeys, currentMonkey)
  35. counter = 0
  36. currentMonkey = monkey{}
  37. continue
  38. }
  39. switch counter {
  40. case 1:
  41. currentMonkey.items = readItems(line)
  42. }
  43. counter++
  44. }
  45. monkeys = append(monkeys, currentMonkey)
  46. return monkeys
  47. }
  48. func main() {
  49. if len(os.Args) < 2 {
  50. log.Fatal("You need to specify a file!")
  51. }
  52. filePath := os.Args[1]
  53. file, err := os.Open(filePath)
  54. if err != nil {
  55. log.Fatalf("Failed to open %s!\n", filePath)
  56. }
  57. monkeys := readInput(file)
  58. fmt.Println(monkeys)
  59. }