code.go 966 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func getNumber(char byte) int {
  9. switch char {
  10. case '2':
  11. return 2
  12. case '1':
  13. return 1
  14. case '0':
  15. return 0
  16. case '-':
  17. return -1
  18. case '=':
  19. return -2
  20. }
  21. return 300
  22. }
  23. func fromSnafu(text string) int {
  24. multiplier := 5
  25. modifier := 1
  26. end := len(text) - 1
  27. result := 0
  28. for i := end; i >= 0; i-- {
  29. n := getNumber(text[i])
  30. result += modifier * n
  31. modifier *= multiplier
  32. }
  33. return result
  34. }
  35. func readInput(file *os.File) []int {
  36. scanner := bufio.NewScanner(file)
  37. var numbers []int
  38. for scanner.Scan() {
  39. line := scanner.Text()
  40. if line == "" {
  41. continue
  42. }
  43. numbers = append(numbers, fromSnafu(line))
  44. }
  45. return numbers
  46. }
  47. func main() {
  48. if len(os.Args) < 2 {
  49. log.Fatal("You need to specify a file!")
  50. }
  51. filePath := os.Args[1]
  52. file, err := os.Open(filePath)
  53. if err != nil {
  54. log.Fatalf("Failed to open %s!\n", filePath)
  55. }
  56. numbers := readInput(file)
  57. fmt.Println(numbers)
  58. }