advent22/api/advent22_api/routers/_misc.py

27 lines
679 B
Python
Raw Normal View History

2022-10-14 22:47:16 +00:00
import itertools
import random
2022-10-14 23:21:14 +00:00
from typing import Any, Sequence
2022-10-14 22:47:16 +00:00
2022-11-04 18:49:31 +00:00
from ..config import get_config
2022-10-14 22:47:16 +00:00
2022-10-14 23:21:14 +00:00
async def get_rnd(bonus_salt: Any = "") -> random.Random:
2022-11-04 18:49:31 +00:00
cfg = await get_config()
return random.Random(f"{cfg.solution}{bonus_salt}")
2022-10-14 23:21:14 +00:00
2022-10-14 22:47:16 +00:00
2022-10-14 23:03:36 +00:00
async def set_length(seq: Sequence, length: int) -> list:
2022-10-14 23:20:35 +00:00
# `seq` unendlich wiederholen
2022-10-14 23:03:36 +00:00
infinite = itertools.cycle(seq)
2022-10-14 23:20:35 +00:00
# Die ersten `length` einträge nehmen
2022-10-14 23:03:36 +00:00
return list(itertools.islice(infinite, length))
2022-10-14 22:47:16 +00:00
2022-10-14 23:21:14 +00:00
async def shuffle(seq: Sequence, rnd: random.Random | None = None) -> list:
2022-10-14 23:20:35 +00:00
# Zufallsgenerator
2022-10-14 23:21:14 +00:00
if rnd is None:
rnd = await get_rnd()
2022-10-14 23:20:35 +00:00
# Elemente mischen
2022-10-14 22:47:16 +00:00
return rnd.sample(seq, len(seq))