Skip to content

Instantly share code, notes, and snippets.

@carloscabo
Created January 28, 2013 14:38
Show Gist options
  • Save carloscabo/4655999 to your computer and use it in GitHub Desktop.
Save carloscabo/4655999 to your computer and use it in GitHub Desktop.
#js #math #utils Cantor pairing. Combines two integer values in a single one that can be reversed to the original ones
//CANTOR PAIRING
/* Combines two integer values in a single one that can be reversed to the original ones */
cantorPair = function(x, y) {
var z = ((x + y) * (x + y + 1)) / 2 + y;
return z;
};
reverseCantorPair = function(z) {
var pair = [];
var t = Math.floor((-1 + Math.sqrt(1 + 8 * z))/2);
var x = t * (t + 3) / 2 - z;
var y = z - t * (t + 1) / 2;
pair[0] = x;
pair[1] = y;
return pair;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment