code.go 928 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type op byte
  9. const (
  10. addx op = iota
  11. noop
  12. )
  13. type command struct {
  14. instruction op
  15. value int
  16. }
  17. func readInput(file *os.File) []command {
  18. scanner := bufio.NewScanner(file)
  19. var commands []command
  20. for scanner.Scan() {
  21. line := scanner.Text()
  22. if line == "" {
  23. continue
  24. }
  25. var current command
  26. if line[0] == 'n' {
  27. current.instruction = noop
  28. } else {
  29. current.instruction = addx
  30. n, err := fmt.Sscanf(line, "addx %d", &current.value)
  31. if n != 1 || err != nil {
  32. log.Fatal("Can't parse input:", err, line)
  33. }
  34. }
  35. commands = append(commands, current)
  36. }
  37. return commands
  38. }
  39. func main() {
  40. if len(os.Args) < 2 {
  41. log.Fatal("You need to specify a file!")
  42. }
  43. filePath := os.Args[1]
  44. file, err := os.Open(filePath)
  45. if err != nil {
  46. log.Fatalf("Failed to open %s!\n", filePath)
  47. }
  48. commands := readInput(file)
  49. fmt.Println(commands)
  50. }