You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 line
2.3KB

  1. import collections
  2. import hashlib
  3. import itertools
  4. import math
  5. import os
  6. import re
  7. import sys
  8. from pathlib import Path
  9. import requests
  10. def lcm(a, b):
  11. return abs(a * b) // math.gcd(a, b)
  12. def render(grid, brush=None):
  13. if brush is None:
  14. brush = {v: v for v in grid.values()}
  15. if isinstance(brush, str):
  16. brush = {i: c for i, c in enumerate(brush)}
  17. xmin, *_, xmax = sorted(int(p.real) for p in grid)
  18. ymin, *_, ymax = sorted(int(p.imag) for p in grid)
  19. brush[None] = ' '
  20. rendered = ''
  21. for y in range(ymin, ymax + 1):
  22. for x in range(xmin, xmax + 1):
  23. rendered += brush[grid.get(complex(x, y))]
  24. rendered += '\n'
  25. return rendered
  26. def read_image(text):
  27. grid = collections.defaultdict(str)
  28. for y, line in enumerate(text.splitlines()):
  29. for x, cell in enumerate(line):
  30. grid[complex(x, y)] = cell
  31. return grid, x + 1, y + 1
  32. def shortest_path(start, end, move):
  33. seen = {}
  34. edge = {start: None}
  35. while edge:
  36. seen.update(edge)
  37. edge = {
  38. adj: pos
  39. for pos in edge
  40. for adj in move(pos)
  41. if adj not in seen
  42. }
  43. if end in seen:
  44. break
  45. else:
  46. raise RuntimeError('Path not found', seen)
  47. path = []
  48. while end:
  49. path.append(end)
  50. end = seen[end]
  51. return path[::-1]
  52. def get_dat():
  53. path = sys.argv[1]
  54. year, qn = map(int, re.findall(r'\d+', sys.argv[1]))
  55. url = f'https://adventofcode.com/{year}/day/{qn}/input'
  56. cookies = {'session': os.environ['SESSION']}
  57. response = requests.get(url, cookies=cookies)
  58. response.raise_for_status()
  59. Path(path).write_bytes(response.content)
  60. def batch(iterable, size):
  61. count = itertools.count()
  62. for _, sub in itertools.groupby(iterable, lambda _: next(count) // size):
  63. yield sub
  64. def md5(string):
  65. return hashlib.md5(string.encode()).hexdigest()
  66. def loop_consume(lines, handler):
  67. instructions = collections.deque(lines)
  68. count = 0
  69. while instructions:
  70. ok = handler(instructions[0])
  71. if ok:
  72. instructions.popleft()
  73. count = 0
  74. elif count < len(instructions):
  75. instructions.rotate(1)
  76. count += 1
  77. else:
  78. raise RuntimeError('Reached steady state')