code.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. )
  9. func readInput(file *os.File) []int {
  10. scanner := bufio.NewScanner(file)
  11. var numbers []int
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. break
  16. }
  17. number, err := strconv.Atoi(line)
  18. if err != nil {
  19. log.Fatalf("Can't parse a number %s: %s", line, err)
  20. }
  21. numbers = append(numbers, number)
  22. }
  23. return numbers
  24. }
  25. func calculate(number int) int {
  26. a := number * 64
  27. number = (number ^ a) % 16777216
  28. b := number / 32
  29. number = (number ^ b) % 16777216
  30. c := number * 2048
  31. number = (number ^ c) % 16777216
  32. return number
  33. }
  34. func generateNumber(number int, iterations int) (int, []int) {
  35. lastDigits := make([]int, iterations+1)
  36. lastDigits[0] = number % 10
  37. for i := 0; i < iterations; i++ {
  38. number = calculate(number)
  39. lastDigits[i+1] = number % 10
  40. }
  41. return number, lastDigits
  42. }
  43. func part1(numbers []int, iterations int) (int, [][]int) {
  44. var result int
  45. var allLastDigits [][]int
  46. for _, number := range numbers {
  47. newNumber, lastDigits := generateNumber(number, iterations)
  48. result += newNumber
  49. allLastDigits = append(allLastDigits, lastDigits)
  50. }
  51. return result, allLastDigits
  52. }
  53. func main() {
  54. if len(os.Args) < 2 {
  55. log.Fatal("You need to specify a file!")
  56. }
  57. filePath := os.Args[1]
  58. file, err := os.Open(filePath)
  59. if err != nil {
  60. log.Fatalf("Failed to open %s!\n", filePath)
  61. }
  62. numbers := readInput(file)
  63. part1Result, allLastDigits := part1(numbers, 2000)
  64. fmt.Println("Part1:", part1Result)
  65. fmt.Println(allLastDigits)
  66. }