day25.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 establishLoopSize(key int) int {
  29. iterations := 0
  30. value := 1
  31. for value != key {
  32. value *= 7
  33. value %= 20201227
  34. iterations++
  35. }
  36. return iterations
  37. }
  38. func transform(subject int, iterations int) int {
  39. value := 1
  40. for i := 0; i < iterations; i++ {
  41. value *= subject
  42. value %= 20201227
  43. }
  44. return value
  45. }
  46. func main() {
  47. if len(os.Args) < 2 {
  48. log.Fatal("You need to specify a file!")
  49. }
  50. filePath := os.Args[1]
  51. file, err := os.Open(filePath)
  52. if err != nil {
  53. log.Fatalf("Failed to open %s!\n", filePath)
  54. }
  55. keys := readFile(file)
  56. if err := file.Close(); err != nil {
  57. log.Fatalf("Failed to close file: %s", err)
  58. }
  59. key1LoopSize := establishLoopSize(keys[0])
  60. key2LoopSize := establishLoopSize(keys[1])
  61. encryptionKey1 := transform(keys[1], key1LoopSize)
  62. encryptionKey2 := transform(keys[0], key2LoopSize)
  63. if encryptionKey1 == encryptionKey2 {
  64. fmt.Println("Part1:", encryptionKey1)
  65. }
  66. }