Skip to content

Instantly share code, notes, and snippets.

@danwald
Last active April 12, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danwald/994c415be8fd2a135816817d28ec71fd to your computer and use it in GitHub Desktop.
Save danwald/994c415be8fd2a135816817d28ec71fd to your computer and use it in GitHub Desktop.
'''
encodes a pair of +ive ints to an int and complementary method
src: http://mathforum.org/library/drmath/view/56036.html
'''
def encode_pair(a: int, b: int) -> int:
'''
implements
[(a + b)^2 + 3a + b]/2
a - positive int
b - positive int
'''
try:
a, b = int(a), int(b)
except TypeError:
raise
else:
if a <= 0 or b <= 0:
raise ValueError('invalid input. Numbers to encode should be positive integers')
return int(((a + b)**2 + (3 * a) + b) / 2)
def decode_pair(N: int) -> (int, int):
'''
implements
c = int[[sqrt(8N + 1) - 1]/2]
a = N - c(c + 1)/2
b = c(c + 3)/2 - N
N - +ive int > 3
return (a - +int, b: +int)
'''
try:
N = int(N)
except TypeError:
raise
else:
if N < 4:
raise ValueError('Number to decode should be less than 4')
c = int(((8 * N + 1)**0.5 - 1) / 2)
a = N - c * (c + 1) / 2
b = c * (c + 3) / 2 - N
return int(a), int(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment