code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type round struct {
  9. elf byte
  10. me byte
  11. score int
  12. }
  13. func fight(elf byte, me byte) int {
  14. if me == 'X' && elf == 'C' {
  15. return 6
  16. } else if me == 'Z' && elf == 'B' {
  17. return 6
  18. } else if me == 'Y' && elf == 'A' {
  19. return 6
  20. }
  21. return 0
  22. }
  23. func readInput(file *os.File, points map[byte]int) []round {
  24. scanner := bufio.NewScanner(file)
  25. var rounds []round
  26. for scanner.Scan() {
  27. line := scanner.Text()
  28. if line == "" {
  29. continue
  30. }
  31. var elf byte
  32. var me byte
  33. n, err := fmt.Sscanf(line, "%c %c", &elf, &me)
  34. if n != 2 || err != nil {
  35. log.Fatal("Can't parse input")
  36. }
  37. score := 0
  38. if points[elf] == points[me] {
  39. score += 3
  40. } else {
  41. score += fight(elf, me)
  42. }
  43. score += points[me]
  44. rounds = append(rounds, round{elf, me, score})
  45. }
  46. return rounds
  47. }
  48. func roundsScore(rounds []round) int {
  49. sum := 0
  50. for i := range rounds {
  51. sum += rounds[i].score
  52. }
  53. return sum
  54. }
  55. func part2(rounds []round, winLose map[byte][2]byte, points map[byte]int) int {
  56. total := 0
  57. for i := range rounds {
  58. if rounds[i].me == 'Y' {
  59. total += 3 + points[rounds[i].elf]
  60. } else if rounds[i].me == 'X' {
  61. total += points[winLose[rounds[i].elf][1]]
  62. } else {
  63. total += 6 + points[winLose[rounds[i].elf][0]]
  64. }
  65. }
  66. return total
  67. }
  68. func main() {
  69. if len(os.Args) < 2 {
  70. log.Fatal("You need to specify a file!")
  71. }
  72. filePath := os.Args[1]
  73. file, err := os.Open(filePath)
  74. if err != nil {
  75. log.Fatalf("Failed to open %s!\n", filePath)
  76. }
  77. points := make(map[byte]int)
  78. points['A'] = 1
  79. points['X'] = 1
  80. points['B'] = 2
  81. points['Y'] = 2
  82. points['C'] = 3
  83. points['Z'] = 3
  84. rounds := readInput(file, points)
  85. fmt.Println("Part1:", roundsScore(rounds))
  86. winLose := make(map[byte][2]byte)
  87. winLose['A'] = [2]byte{'Y', 'Z'}
  88. winLose['B'] = [2]byte{'Z', 'X'}
  89. winLose['C'] = [2]byte{'X', 'Y'}
  90. fmt.Println("Part2:", part2(rounds, winLose, points))
  91. }