2020: d05: ex2: add solution
This commit is contained in:
parent
e8d61b3cf8
commit
a9539a3416
63
2021/d05/ex2/ex2.py
Executable file
63
2021/d05/ex2/ex2.py
Executable file
|
@ -0,0 +1,63 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
import sys
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Iterable, List, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Point:
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
|
||||||
|
|
||||||
|
Line = Tuple[Point, Point]
|
||||||
|
|
||||||
|
|
||||||
|
def solve(input: List[str]) -> int:
|
||||||
|
def parse_line(line: str) -> Line:
|
||||||
|
def parse_point(point: str) -> Point:
|
||||||
|
x, y = map(int, point.split(","))
|
||||||
|
return Point(x, y)
|
||||||
|
|
||||||
|
p1, p2 = map(parse_point, line.split(" -> "))
|
||||||
|
return (p1, p2)
|
||||||
|
|
||||||
|
def line_to_points(line: Line) -> Iterable[Point]:
|
||||||
|
def inclusive_range_any_order(a: int, b: int) -> Iterable[int]:
|
||||||
|
if a < b:
|
||||||
|
yield from range(a, b + 1)
|
||||||
|
else:
|
||||||
|
yield from range(a, b - 1, -1)
|
||||||
|
|
||||||
|
p1, p2 = line
|
||||||
|
|
||||||
|
if p1.x == p2.x:
|
||||||
|
for y in inclusive_range_any_order(p1.y, p2.y):
|
||||||
|
yield (p1.x, y)
|
||||||
|
return
|
||||||
|
|
||||||
|
if p1.y == p2.y:
|
||||||
|
for x in inclusive_range_any_order(p1.x, p2.x):
|
||||||
|
yield (x, p1.y)
|
||||||
|
return
|
||||||
|
|
||||||
|
step = 1 if p1.x < p2.x else -1
|
||||||
|
for i, y in enumerate(inclusive_range_any_order(p1.y, p2.y)):
|
||||||
|
yield (p1.x + i * step, y)
|
||||||
|
|
||||||
|
lines = list(map(parse_line, input))
|
||||||
|
counts = Counter(itertools.chain.from_iterable(line_to_points(l) for l in lines))
|
||||||
|
|
||||||
|
return sum(counts[p] > 1 for p in counts)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
input = [line.strip() for line in sys.stdin.readlines()]
|
||||||
|
print(solve(input))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
Loading…
Reference in a new issue