Compare commits

..

3 commits

Author SHA1 Message Date
Bruno BELANYI 841830555c 2022: d14: ex2: add solution 2022-12-14 14:42:06 +01:00
Bruno BELANYI 1da934eae6 2022: d14: ex2: add input 2022-12-14 14:42:01 +01:00
Bruno BELANYI 14ec9baf77 2022: d14: ex1: add solution 2022-12-14 14:41:54 +01:00
2 changed files with 12 additions and 14 deletions

View file

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