solution.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/python3
  2. import sys
  3. def pattern_str(pattern):
  4. return '\n'.join([''.join(line) for line in pattern])
  5. def rotate(pattern):
  6. return [list(line) for line in zip(*reversed(pattern))]
  7. def is_reflected(up, down, k):
  8. for l in range(min(len(up), len(down))):
  9. i, j = k - l - 1, l
  10. if up[i] != down[j]:
  11. return False
  12. return True
  13. def get_reflection(pattern):
  14. total = len(pattern)
  15. for k in range(1, len(pattern)):
  16. print(f'k={k}')
  17. if is_reflected(pattern[:k], pattern[k:], k):
  18. return k
  19. return -1
  20. def is_reflected_with_correction(up, down, k):
  21. correction = True
  22. for l in range(min(len(up), len(down))):
  23. i, j = k - l - 1, l
  24. if up[i] != down[j] and correction:
  25. different = [(u, d) for u, d in zip(up[i], down[j]) if u != d]
  26. if len(different) == 1:
  27. #print(different, len(different))
  28. correction = False
  29. continue
  30. else:
  31. return False
  32. elif up[i] != down[j]:
  33. return False
  34. return not correction
  35. def get_reflection_with_correction(pattern):
  36. total = len(pattern)
  37. max_k = -1
  38. for k in range(1, len(pattern)):
  39. #print(f'k={k}')
  40. if is_reflected_with_correction(pattern[:k], pattern[k:], k):
  41. max_k = max(max_k, k)
  42. return max_k
  43. def part12(correction=False):
  44. print('part 1')
  45. patterns = [[]]
  46. for line in map(lambda line: line.strip(), sys.stdin):
  47. if len(line) == 0:
  48. patterns.append([])
  49. else:
  50. patterns[-1].append(list(line))
  51. total = 0
  52. for i, pattern in enumerate(patterns):
  53. print(f'pattern {i}:\n{pattern_str(pattern)}\nrotated:\n{pattern_str(rotate(pattern))}')
  54. reflection = get_reflection_with_correction(pattern) if correction else get_reflection(pattern)
  55. if reflection > 0:
  56. print(f'found horizontal reflection at {reflection}')
  57. total += 100 * reflection
  58. continue
  59. rotated = rotate(pattern)
  60. reflection = get_reflection_with_correction(rotated) if correction else get_reflection(rotated)
  61. if reflection > 0:
  62. print(f'found vertical reflection at {reflection}')
  63. total += reflection
  64. print(total)
  65. if sys.argv[1] in '1':
  66. part12(correction=False)
  67. else:
  68. part12(correction=True)