Skip to content

Instantly share code, notes, and snippets.

@defp
Last active December 17, 2020 05:02
Show Gist options
  • Save defp/f3eae5394dd8285a1dc81584743f99fa to your computer and use it in GitHub Desktop.
Save defp/f3eae5394dd8285a1dc81584743f99fa to your computer and use it in GitHub Desktop.
SzudzikPairing
// 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
}
}
# 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
@defp
Copy link
Author

defp commented Dec 16, 2020

@defp
Copy link
Author

defp commented Dec 17, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment