code.go 1.8 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. const multiplier int = 5
  24. func fromSnafu(text string) int {
  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 abs(number int) int {
  70. if number < 0 {
  71. return 0 - number
  72. }
  73. return number
  74. }
  75. func reverse(bytes []byte) []byte {
  76. edge := len(bytes) - 1
  77. var reversed []byte
  78. for i := edge; i >= 0; i-- {
  79. reversed = append(reversed, bytes[i])
  80. }
  81. return reversed
  82. }
  83. func toSnafu(number int) string {
  84. var result []byte
  85. for {
  86. if number <= 0 {
  87. break
  88. }
  89. rem := number % multiplier
  90. number /= multiplier
  91. if rem == 3 {
  92. rem = -2
  93. number += 1
  94. } else if rem == 4 {
  95. rem = -1
  96. number++
  97. }
  98. result = append(result, getChar(rem))
  99. }
  100. return string(reverse(result))
  101. }
  102. func main() {
  103. if len(os.Args) < 2 {
  104. log.Fatal("You need to specify a file!")
  105. }
  106. filePath := os.Args[1]
  107. file, err := os.Open(filePath)
  108. if err != nil {
  109. log.Fatalf("Failed to open %s!\n", filePath)
  110. }
  111. numbers := readInput(file)
  112. sum := sum(numbers)
  113. fmt.Println("Part1:", toSnafu(sum))
  114. }