Last active
December 17, 2020 05:02
-
-
Save defp/f3eae5394dd8285a1dc81584743f99fa to your computer and use it in GitHub Desktop.
SzudzikPairing
This file contains 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
// run https://play.golang.org/p/gVl4Ru_isVA | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func main() { | |
fmt.Println(pair(168, 701)) | |
fmt.Println(pair(100454, 491569)) | |
a, b := unPair(241640182215) | |
c, d := unPair(b) | |
fmt.Println(a, c, d) | |
} | |
func pair(x, y uint64) uint64 { | |
if x < y { | |
return x + y*y | |
} else { | |
return x*x + x + y | |
} | |
} | |
func unPair(z uint64) (x, y uint64) { | |
zsf := uint64(math.Floor(math.Sqrt(float64(z)))) | |
zsfzsf := zsf * zsf | |
z_zsfzsf := z - zsfzsf | |
if z_zsfzsf < zsf { | |
return z_zsfzsf, zsf | |
} else { | |
return zsf, z_zsfzsf - zsf | |
} | |
} |
This file contains 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
# Szudzik Pairing Function. | |
# See [paper]( http://szudzik.com/ElegantPairing.pdf and discussion http://stackoverflow.com/a/13871379/667158?stw=2 ) | |
class SzudzikPairing | |
class << self | |
def pair(x, y) | |
if x < y then | |
return x + y * y | |
else | |
return x * x + x + y | |
end | |
end | |
def unpair(z) | |
zsf = Math.sqrt(z).floor | |
zsfzsf = zsf * zsf | |
z_zsfzsf = z - zsfzsf | |
if z_zsfzsf < zsf then | |
return z_zsfzsf, zsf | |
else | |
return zsf, z_zsfzsf - zsf | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python version
https://gitlab.com/snippets/32559