code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 sum(numbers []int) int {
  48. sum := 0
  49. for i := range numbers {
  50. sum += numbers[i]
  51. }
  52. return sum
  53. }
  54. func getChar(number int) byte {
  55. switch number {
  56. case 2:
  57. return '2'
  58. case 1:
  59. return '1'
  60. case 0:
  61. return '0'
  62. case -1:
  63. return '-'
  64. case -2:
  65. return '='
  66. }
  67. return ' '
  68. }
  69. func toSnafu(number int) string {
  70. multiplier := 5
  71. modifier := 1
  72. count := 1
  73. var result []byte
  74. found := false
  75. toMatch := 0
  76. for {
  77. for i := 1; i < 3; i++ {
  78. if i*modifier >= number {
  79. found = true
  80. result = append(result, getChar(i))
  81. toMatch = modifier*i - number
  82. break
  83. }
  84. }
  85. if found {
  86. break
  87. }
  88. modifier *= multiplier
  89. count++
  90. }
  91. for i := 1; i < count; i++ {
  92. modifier /= multiplier
  93. for j := -2; j <= 2; j++ {
  94. p := j * modifier
  95. delta := toMatch + p
  96. if delta >= 0 || 0-delta < 2*modifier/multiplier {
  97. result = append(result, getChar(j))
  98. toMatch = delta
  99. break
  100. }
  101. }
  102. }
  103. return string(result)
  104. }
  105. func main() {
  106. if len(os.Args) < 2 {
  107. log.Fatal("You need to specify a file!")
  108. }
  109. filePath := os.Args[1]
  110. file, err := os.Open(filePath)
  111. if err != nil {
  112. log.Fatalf("Failed to open %s!\n", filePath)
  113. }
  114. numbers := readInput(file)
  115. sum := sum(numbers)
  116. fmt.Println(sum)
  117. fmt.Println(toSnafu(sum))
  118. }