Created
April 21, 2021 12:02
-
-
Save albertotb/be32f265fa285608d064c81c058d12ec to your computer and use it in GitHub Desktop.
Szudzik pairing for negative numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from typing import Tuple | |
def pair_negative(x: int) -> int: | |
return 2 * x if x >= 0 else -2 * x - 1 | |
def unpair_negative(z: int) -> int: | |
return int(z / 2) if z % 2 == 0 else int((z + 1) / -2) | |
def pair_szudzik(x: int, y: int) -> int: | |
a, b = pair_negative(x), pair_negative(y) | |
return a ** 2 + a + b if a >= b else b ** 2 + a | |
def unpair_szudzik(index: int) -> Tuple[int, int]: | |
sqrtz = math.floor(math.sqrt(index)) | |
sqz = sqrtz * sqrtz | |
a, b = (sqrtz, index - sqz - sqrtz) if (index - sqz) >= sqrtz else (index - sqz, sqrtz) | |
return unpair_negative(a), unpair_negative(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment