code.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type Register struct {
  11. id byte
  12. value int
  13. }
  14. func readInput(file *os.File) ([]Register, []int) {
  15. scanner := bufio.NewScanner(file)
  16. var registers []Register
  17. var program []int
  18. var registersRead bool
  19. for scanner.Scan() {
  20. line := scanner.Text()
  21. if line == "" {
  22. registersRead = true
  23. continue
  24. }
  25. if !registersRead {
  26. var register Register
  27. n, err := fmt.Sscanf(line, "Register %c: %d", &register.id, &register.value)
  28. if n != 2 || err != nil {
  29. log.Fatalf("Not able to parse register '%s': %s", line, err)
  30. }
  31. registers = append(registers, register)
  32. } else {
  33. numString := strings.TrimPrefix(line, "Program: ")
  34. parts := strings.Split(numString, ",")
  35. for _, part := range parts {
  36. num, err := strconv.Atoi(part)
  37. if err != nil {
  38. log.Fatalf("Not able to convert %s: %s", part, err)
  39. }
  40. program = append(program, num)
  41. }
  42. }
  43. }
  44. return registers, program
  45. }
  46. func main() {
  47. if len(os.Args) < 2 {
  48. log.Fatal("You need to specify a file!")
  49. }
  50. filePath := os.Args[1]
  51. file, err := os.Open(filePath)
  52. if err != nil {
  53. log.Fatalf("Failed to open %s!\n", filePath)
  54. }
  55. registers, program := readInput(file)
  56. fmt.Println(registers, program)
  57. }