code.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func readLine(line string, arr []int) {
  9. for i := range line {
  10. if line[i] == '#' {
  11. arr[i]++
  12. }
  13. }
  14. }
  15. func readInput(file *os.File) ([][]int, [][]int) {
  16. scanner := bufio.NewScanner(file)
  17. var locks, keys [][]int
  18. var isKey bool
  19. var index int
  20. arr := make([]int, 5)
  21. for scanner.Scan() {
  22. line := scanner.Text()
  23. if line == "" {
  24. if isKey {
  25. keys = append(keys, arr)
  26. } else {
  27. locks = append(locks, arr)
  28. }
  29. arr = make([]int, 5)
  30. index = 0
  31. continue
  32. }
  33. if index == 0 {
  34. isKey = line[0] == '.'
  35. }
  36. if index != 0 && index != 6 {
  37. readLine(line, arr)
  38. }
  39. index++
  40. }
  41. if isKey {
  42. keys = append(keys, arr)
  43. } else {
  44. locks = append(locks, arr)
  45. }
  46. return locks, keys
  47. }
  48. func countMatches(locks, keys [][]int) int {
  49. var count int
  50. for _, lock := range locks {
  51. for _, key := range keys {
  52. fits := true
  53. for i := range lock {
  54. if lock[i]+key[i] > 5 {
  55. fits = false
  56. break
  57. }
  58. }
  59. if fits {
  60. count++
  61. }
  62. }
  63. }
  64. return count
  65. }
  66. func main() {
  67. if len(os.Args) < 2 {
  68. log.Fatal("You need to specify a file!")
  69. }
  70. filePath := os.Args[1]
  71. file, err := os.Open(filePath)
  72. if err != nil {
  73. log.Fatalf("Failed to open %s!\n", filePath)
  74. }
  75. locks, keys := readInput(file)
  76. fmt.Println("Part1:", countMatches(locks, keys))
  77. }