day22.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. )
  9. func readFile(file *os.File) [2][]int {
  10. var decks [2][]int
  11. index := 0
  12. changed := false
  13. scanner := bufio.NewScanner(file)
  14. for scanner.Scan() {
  15. line := scanner.Text()
  16. if line == "" {
  17. if changed {
  18. break
  19. }
  20. continue
  21. }
  22. if line == "Player 1:" {
  23. continue
  24. }
  25. if line == "Player 2:" {
  26. index++
  27. changed = true
  28. continue
  29. }
  30. card, err := strconv.Atoi(line)
  31. if err != nil {
  32. log.Fatalf("Error processing card for %s: %s", line, err)
  33. }
  34. decks[index] = append(decks[index], card)
  35. }
  36. if err := scanner.Err(); err != nil {
  37. log.Fatalf("Scanner error: %s", err)
  38. }
  39. return decks
  40. }
  41. func play(decks [2][]int) []int {
  42. for {
  43. if len(decks[0]) == 0 || len(decks[1]) == 0 {
  44. break
  45. }
  46. player1Hand := decks[0][0]
  47. decks[0] = decks[0][1:len(decks[0])]
  48. player2Hand := decks[1][0]
  49. decks[1] = decks[1][1:len(decks[1])]
  50. if player1Hand > player2Hand {
  51. decks[0] = append(decks[0], player1Hand)
  52. decks[0] = append(decks[0], player2Hand)
  53. } else {
  54. decks[1] = append(decks[1], player2Hand)
  55. decks[1] = append(decks[1], player1Hand)
  56. }
  57. }
  58. if len(decks[0]) == 0 {
  59. return decks[1]
  60. }
  61. return decks[0]
  62. }
  63. func part1(deck []int) int {
  64. result := 0
  65. multiplyBy := 1
  66. index := len(deck) - 1
  67. for ; index >= 0; index-- {
  68. result += deck[index] * multiplyBy
  69. multiplyBy++
  70. }
  71. return result
  72. }
  73. func main() {
  74. if len(os.Args) < 2 {
  75. log.Fatal("You need to specify a file!")
  76. }
  77. filePath := os.Args[1]
  78. file, err := os.Open(filePath)
  79. if err != nil {
  80. log.Fatalf("Failed to open %s!\n", filePath)
  81. }
  82. decks := readFile(file)
  83. if err := file.Close(); err != nil {
  84. log.Fatalf("Failed to close file: %s", err)
  85. }
  86. winningDeck := play(decks)
  87. fmt.Println("Part1:", part1(winningDeck))
  88. }