day25.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. )
  9. func readFile(file *os.File) []int {
  10. var keys []int
  11. scanner := bufio.NewScanner(file)
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. break
  16. }
  17. key, err := strconv.Atoi(string(line))
  18. if err != nil {
  19. log.Fatalf("Error processing key for %s: %s", line, err)
  20. }
  21. keys = append(keys, key)
  22. }
  23. if err := scanner.Err(); err != nil {
  24. log.Fatalf("Scanner error: %s", err)
  25. }
  26. return keys
  27. }
  28. func transformValue(value, subject int) int {
  29. value *= subject
  30. value %= 20201227
  31. return value
  32. }
  33. func establishLoopSize(key int) int {
  34. iterations := 0
  35. value := 1
  36. for value != key {
  37. value = transformValue(value, 7)
  38. iterations++
  39. }
  40. return iterations
  41. }
  42. func transform(subject, iterations int) int {
  43. value := 1
  44. for i := 0; i < iterations; i++ {
  45. value = transformValue(value, subject)
  46. }
  47. return value
  48. }
  49. func main() {
  50. if len(os.Args) < 2 {
  51. log.Fatal("You need to specify a file!")
  52. }
  53. filePath := os.Args[1]
  54. file, err := os.Open(filePath)
  55. if err != nil {
  56. log.Fatalf("Failed to open %s!\n", filePath)
  57. }
  58. keys := readFile(file)
  59. if err := file.Close(); err != nil {
  60. log.Fatalf("Failed to close file: %s", err)
  61. }
  62. key1LoopSize := establishLoopSize(keys[0])
  63. key2LoopSize := establishLoopSize(keys[1])
  64. encryptionKey1 := transform(keys[1], key1LoopSize)
  65. encryptionKey2 := transform(keys[0], key2LoopSize)
  66. if encryptionKey1 == encryptionKey2 {
  67. fmt.Println("Part1:", encryptionKey1)
  68. }
  69. }