Skip to content

Instantly share code, notes, and snippets.

@bussiere
Forked from dyoo/cantor_pairing.go
Created February 14, 2020 20:14
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 bussiere/ebffb950690f5561cc19ddf93bdd30c1 to your computer and use it in GitHub Desktop.
Save bussiere/ebffb950690f5561cc19ddf93bdd30c1 to your computer and use it in GitHub Desktop.
Cantor pairing function
// http://en.wikipedia.org/wiki/Pairing_function
package main
import (
"fmt"
"math"
)
func InvertedCantorPairing(z int) (int, int) {
w := int(math.Floor((math.Sqrt(float64(8*z+1)) - 1) / 2))
t := (w*w + w) / 2
y := z - t
x := w - y
return x, y
}
func CantorPairing(k1, k2 int) int {
return (k1+k2)*(k1+k2+1)/2 + k2
}
func main() {
for i := 0; i < 100; i++ {
x, y := InvertedCantorPairing(i)
fmt.Println(i, x, y, CantorPairing(x, y))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment