-
-
Save PatrikMelanderVing/62b516bd5c92432a616f9caf88f3e55b to your computer and use it in GitHub Desktop.
Simple C# class to calculate Cantor's pairing function
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
using System; | |
public static class CantorPairUtility { | |
public static int CantorPair(int x, int y) { | |
return (((x + y) * (x + y + 1)) / 2) + y; | |
} | |
public static void ReverseCantorPair(int cantor, out int x, out int y) { | |
var t = (int) Math.Floor((-1 + Math.Sqrt(1 + 8 * cantor)) / 2); | |
x = t * (t + 3) / 2 - cantor; | |
y = cantor - t * (t + 1) / 2; | |
} | |
public static int SignedCantorPair(int x, int y) { | |
x = x >= 0 ? 2 * x : -2 * x + 1; | |
y = y >= 0 ? 2 * y : -2 * y + 1; | |
return (((x + y) * (x + y + 1)) / 2) + y; | |
} | |
public static void SignedReverseCantorPair(int cantor, out int x, out int y) { | |
var t = (int) Math.Floor((-1 + Math.Sqrt(1 + 8 * cantor)) / 2); | |
x = t * (t + 3) / 2 - cantor; | |
y = cantor - t * (t + 1) / 2; | |
x = x % 2 == 0 ? x / 2 : ((1 - x) / 2); | |
y = y % 2 == 0 ? y / 2 : ((1 - y) / 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment