Skip to content

Instantly share code, notes, and snippets.

@NekitoSP
Forked from GibsS/CantorPairUtility.cs
Created May 3, 2020 12:12
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 NekitoSP/4aa0d1e00a82ead018ffae506c7d777f to your computer and use it in GitHub Desktop.
Save NekitoSP/4aa0d1e00a82ead018ffae506c7d777f to your computer and use it in GitHub Desktop.
Simple C# class to calculate Cantor's pairing function
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