Skip to content

Instantly share code, notes, and snippets.

@TheGreatRambler
Last active August 7, 2024 14:57
Show Gist options
  • Save TheGreatRambler/048f4b38ca561e6566e0e0f6e71b7739 to your computer and use it in GitHub Desktop.
Save TheGreatRambler/048f4b38ca561e6566e0e0f6e71b7739 to your computer and use it in GitHub Desktop.
A pairing function (szudzik) that supports negative numbers
// src https://codepen.io/sachmata/post/elegant-pairing
szudzik.getindex = function(x, y) {
var xx = x >= 0 ? x * 2 : x * -2 - 1;
var yy = y >= 0 ? y * 2 : y * -2 - 1;
return (xx >= yy) ? (xx * xx + xx + yy) : (yy * yy + xx);
};
szudzik.unpair = function(z) {
var sqrtz = Math.floor(Math.sqrt(z));
var sqz = sqrtz * sqrtz;
var result1 = ((z - sqz) >= sqrtz) ? [sqrtz, z - sqz - sqrtz] : [z - sqz, sqrtz];
var xx = result1[0] % 2 === 0 ? result1[0] / 2 : (result1[0] + 1) / -2;
var yy = result1[1] % 2 === 0 ? result1[1] / 2 : (result1[1] + 1) / -2;
return [xx, yy];
};
@Th0rgal
Copy link

Th0rgal commented Oct 8, 2021

Thanks nick and TheGreatRambler!

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