code.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 checkTowel(towel string, index int, patterns [][]string) bool {
  33. if index >= len(towel) {
  34. return true
  35. }
  36. for _, pattern := range patterns[towel[index]-delta] {
  37. patternMatch := true
  38. for i := range pattern {
  39. if index+i >= len(towel) || pattern[i] != towel[index+i] {
  40. patternMatch = false
  41. break
  42. }
  43. }
  44. if patternMatch && checkTowel(towel, index+len(pattern), patterns) {
  45. return true
  46. }
  47. }
  48. return false
  49. }
  50. func part1(patterns [][]string, towels []string) int {
  51. var count int
  52. for _, towel := range towels {
  53. if checkTowel(towel, 0, patterns) {
  54. count++
  55. }
  56. }
  57. return count
  58. }
  59. func main() {
  60. if len(os.Args) < 2 {
  61. log.Fatal("You need to specify a file!")
  62. }
  63. filePath := os.Args[1]
  64. file, err := os.Open(filePath)
  65. if err != nil {
  66. log.Fatalf("Failed to open %s!\n", filePath)
  67. }
  68. patterns, towels := readInput(file)
  69. fmt.Println("Part1:", part1(patterns, towels))
  70. }