code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type rucksack struct {
  9. first map[byte]int
  10. second map[byte]int
  11. }
  12. func readInput(file *os.File) []rucksack {
  13. scanner := bufio.NewScanner(file)
  14. var rucksacks []rucksack
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. continue
  19. }
  20. edge := len(line)
  21. half := edge / 2
  22. start := 0
  23. current := rucksack{make(map[byte]int), make(map[byte]int)}
  24. for {
  25. if half >= edge {
  26. break
  27. }
  28. current.first[line[start]]++
  29. current.second[line[half]]++
  30. start++
  31. half++
  32. }
  33. rucksacks = append(rucksacks, current)
  34. }
  35. return rucksacks
  36. }
  37. func getPriority(item byte) int {
  38. if item < 96 {
  39. return int(item) - 38
  40. }
  41. return int(item) - 96
  42. }
  43. func part1(rucksacks []rucksack) int {
  44. sum := 0
  45. for i := range rucksacks {
  46. for key, _ := range rucksacks[i].first {
  47. if rucksacks[i].second[key] > 0 {
  48. sum += getPriority(key)
  49. }
  50. }
  51. }
  52. return sum
  53. }
  54. func checkCompartments(compartment map[byte]int, rucksacks []rucksack, index int) int {
  55. for key, _ := range compartment {
  56. if rucksacks[index+1].first[key] == 0 && rucksacks[index+1].second[key] == 0 {
  57. continue
  58. }
  59. if rucksacks[index+2].first[key] == 0 && rucksacks[index+2].second[key] == 0 {
  60. continue
  61. }
  62. return getPriority(key)
  63. }
  64. return 0
  65. }
  66. func part2(rucksacks []rucksack) int {
  67. edge := len(rucksacks) - 2
  68. index := 0
  69. sum := 0
  70. for {
  71. if index >= edge {
  72. break
  73. }
  74. result := checkCompartments(rucksacks[index].first, rucksacks, index)
  75. if result == 0 {
  76. result = checkCompartments(rucksacks[index].second, rucksacks, index)
  77. }
  78. sum += result
  79. index += 3
  80. }
  81. return sum
  82. }
  83. func main() {
  84. if len(os.Args) < 2 {
  85. log.Fatal("You need to specify a file!")
  86. }
  87. filePath := os.Args[1]
  88. file, err := os.Open(filePath)
  89. if err != nil {
  90. log.Fatalf("Failed to open %s!\n", filePath)
  91. }
  92. rucksacks := readInput(file)
  93. fmt.Println("Part1:", part1(rucksacks))
  94. fmt.Println("Part2:", part2(rucksacks))
  95. }