From 37309781de3dd1cd201e7b566ab159a3ff74d89c Mon Sep 17 00:00:00 2001 From: weilycoder Date: Mon, 16 Dec 2024 22:44:15 +0800 Subject: [PATCH] Support generating a random seed from the command-line arguments --- cyaron/utils.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/cyaron/utils.py b/cyaron/utils.py index e61ecfb..78d195b 100644 --- a/cyaron/utils.py +++ b/cyaron/utils.py @@ -1,4 +1,6 @@ -from typing import cast, Any, Dict, Iterable, Tuple, Union +import sys +import random +from typing import List, Optional, cast, Any, Dict, Iterable, Tuple, Union __all__ = [ "ati", @@ -69,3 +71,24 @@ def unpack_kwargs( f"{funcname}() got an unexpected keyword argument '{next(iter(kwargs.items()))[0]}'" ) return rv + + +def get_seed_from_argv(argv: Optional[List[str]] = None): + """ + Calculate a random seed from the command-line arguments, + referencing the implementation of `testlib.h`, but with differing behavior. + + https://github.com/MikeMirzayanov/testlib/blob/9ecb11126c16caeda2ba375e0084b3ddd03d4ace/testlib.h#L800 + """ + seed = 3905348978240129619 + for s in sys.argv[1:] if argv is None else argv: + for c in s: + seed = seed * 0x5DEECE66D + ord(c) + 0xB + seed &= 0xFFFFFFFFFFFF + seed += 0x88A12C38 + return seed & 0xFFFFFFFFFFFF + + +def set_seed_from_argv(argv: Optional[List[str]] = None, version: int = 2): + """Set the random seed from the command-line arguments.""" + random.seed(get_seed_from_argv(argv), version)