Skip to content

Instantly share code, notes, and snippets.

@GibsS
Created May 30, 2018 22:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save GibsS/fdba8e3cdbd307652fc3c01336b32534 to your computer and use it in GitHub Desktop.
Save GibsS/fdba8e3cdbd307652fc3c01336b32534 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);
}
}
@akitasov
Copy link

thank you!

@PatrikMelanderVing
Copy link

Nice, thank you 👍

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