code.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. if line[0] == '.' {
  35. isKey = true
  36. }
  37. }
  38. if index != 0 && index != 6 {
  39. readLine(line, arr)
  40. }
  41. index++
  42. }
  43. if isKey {
  44. keys = append(keys, arr)
  45. } else {
  46. locks = append(locks, arr)
  47. }
  48. return locks, keys
  49. }
  50. func countMatches(locks, keys [][]int) int {
  51. var count int
  52. for _, lock := range locks {
  53. for _, key := range keys {
  54. fits := true
  55. for i := range lock {
  56. if lock[i]+key[i] > 5 {
  57. fits = false
  58. break
  59. }
  60. }
  61. if fits {
  62. count++
  63. }
  64. }
  65. }
  66. return count
  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. locks, keys := readInput(file)
  78. fmt.Println("Part1:", countMatches(locks, keys))
  79. }