code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. const delta byte = 97
  10. func readInput(file *os.File) ([][]string, []string) {
  11. scanner := bufio.NewScanner(file)
  12. patterns := make([][]string, 25)
  13. var towels []string
  14. var patternsRead bool
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. patternsRead = true
  19. continue
  20. }
  21. if !patternsRead {
  22. parts := strings.Split(line, ", ")
  23. for _, part := range parts {
  24. patterns[part[0]-delta] = append(patterns[part[0]-delta], part)
  25. }
  26. } else {
  27. towels = append(towels, line)
  28. }
  29. }
  30. return patterns, towels
  31. }
  32. func patternAndIndex(pattern string, index int) string {
  33. return fmt.Sprintf("%s_%d", pattern, index)
  34. }
  35. func checkTowel(towel string, index int, patterns [][]string, checked map[string]bool) bool {
  36. if index >= len(towel) {
  37. return true
  38. }
  39. for _, pattern := range patterns[towel[index]-delta] {
  40. if checked[patternAndIndex(pattern, index)] {
  41. continue
  42. }
  43. checked[patternAndIndex(pattern, index)] = true
  44. patternMatch := true
  45. for i := range pattern {
  46. if index+i >= len(towel) || pattern[i] != towel[index+i] {
  47. patternMatch = false
  48. break
  49. }
  50. }
  51. if patternMatch && checkTowel(towel, index+len(pattern), patterns, checked) {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. func getPossibleTowers(patterns [][]string, towels []string) []string {
  58. var possible []string
  59. for _, towel := range towels {
  60. checked := make(map[string]bool)
  61. if checkTowel(towel, 0, patterns, checked) {
  62. possible = append(possible, towel)
  63. }
  64. }
  65. return possible
  66. }
  67. func main() {
  68. if len(os.Args) < 2 {
  69. log.Fatal("You need to specify a file!")
  70. }
  71. filePath := os.Args[1]
  72. file, err := os.Open(filePath)
  73. if err != nil {
  74. log.Fatalf("Failed to open %s!\n", filePath)
  75. }
  76. patterns, towels := readInput(file)
  77. possible := getPossibleTowers(patterns, towels)
  78. fmt.Println("Part1:", len(possible))
  79. }