Compare commits

..

3 commits

Author SHA1 Message Date
Bruno BELANYI a9c325ce14 2022: d14: ex2: add solution 2022-12-14 15:00:48 +01:00
Bruno BELANYI e457aaed44 2022: d14: ex2: add input 2022-12-14 15:00:48 +01:00
Bruno BELANYI 2c486e5984 2022: d14: ex1: add solution 2022-12-14 15:00:48 +01:00
2 changed files with 14 additions and 12 deletions

View file

@ -4,7 +4,7 @@ import dataclasses
import itertools
import sys
from collections.abc import Iterator
from typing import NamedTuple
from typing import NamedTuple, Optional
def sign(n: int) -> int:
@ -57,7 +57,7 @@ def solve(input: list[str]) -> int:
for dx, dy in ((0, 1), (-1, 1), (1, 1)):
yield Point(p.x + dx, p.y + dy)
def add_sand(points: set[Point]) -> tuple[bool, set[Point]]:
def add_sand(points: set[Point]) -> Optional[Point]:
start = Point(500, 0)
assert start not in points # Sanity check
@ -65,7 +65,7 @@ def solve(input: list[str]) -> int:
while True:
# Steady state was reached
if start.y >= max_height:
return False, points
return None
viable_candidates = (p for p in sand_candidates(start) if p not in points)
candidate = next(viable_candidates, None)
@ -74,13 +74,14 @@ def solve(input: list[str]) -> int:
break
start = candidate
return True, (points | {start})
return start
res = 0
while True:
added, all_points = add_sand(all_points)
if not added:
grain = add_sand(all_points)
if grain is None:
break
all_points.add(grain)
res += 1
return res

View file

@ -4,7 +4,7 @@ import dataclasses
import itertools
import sys
from collections.abc import Iterator
from typing import NamedTuple
from typing import NamedTuple, Optional
def sign(n: int) -> int:
@ -57,11 +57,11 @@ def solve(input: list[str]) -> int:
for dx, dy in ((0, 1), (-1, 1), (1, 1)):
yield Point(p.x + dx, p.y + dy)
def add_sand(points: set[Point]) -> tuple[bool, set[Point]]:
def add_sand(points: set[Point]) -> Optional[Point]:
start = Point(500, 0)
if start in points:
return False, points
return None
while True:
viable_candidates = (p for p in sand_candidates(start) if p not in points)
@ -74,13 +74,14 @@ def solve(input: list[str]) -> int:
break
start = candidate
return True, (points | {start})
return start
res = 0
while True:
added, all_points = add_sand(all_points)
if not added:
grain = add_sand(all_points)
if grain is None:
break
all_points.add(grain)
res += 1
return res