Created
October 15, 2016 16:20
-
-
Save ast3150/83ee72e435e146bbd6397a8397086903 to your computer and use it in GitHub Desktop.
Cantor Pairing in Swift 3
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
/// Generates a unique integer from the combination of two integers | |
/// using the Cantor Pairing function. | |
/// | |
/// # Examples | |
/// | |
/// f(47, 32) = 3192 | |
/// | |
/// f(32, 47) = 3207 | |
/// | |
/// - seealso: https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function | |
public func pair(_ a: Int, _ b: Int) -> Int { | |
return ((a + b) * (a + b + 1) / 2) + b | |
} | |
/// Resolves a cantor paired integer to its original values | |
/// | |
/// # Examples | |
/// | |
/// f(3192) = (47, 32) | |
/// | |
/// f(3207) = (32, 47) | |
/// | |
/// - seealso: pair(_:_:) | |
public func unpair(_ z: Int) -> (x: Int, y: Int) { | |
let d = Double(z) | |
let t = Int(floor((sqrt(8 * d + 1) - 1) / 2)) | |
let x = t * (t + 3) / 2 - z | |
let y = z - t * (t + 1) / 2 | |
return (x, y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment