Skip to content

Instantly share code, notes, and snippets.

@TheGreatRambler
Last active August 7, 2024 14:57
Show Gist options
  • Select an option

  • Save TheGreatRambler/048f4b38ca561e6566e0e0f6e71b7739 to your computer and use it in GitHub Desktop.

Select an option

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];
};
@nickstheisen
Copy link
Copy Markdown

nickstheisen commented Nov 5, 2019

Hi, i stumbled over your code while looking for a pairing function that works with negative numbers. After I reimplemented it in python I have noticed, that you have a small bug in the else branch of the following lines:

var xx = result1[0] % 2 === 0 ? result1[0] / 2 : result1[0] / -2 + 1;
var yy = result1[1] % 2 === 0 ? result1[1] / 2 : result1[1] / -2 + 1;

. In the else-branches of your getindex function you multiply x respectively y with -2 and then subtract 1 from the result. Therefore to invert this part of the function you need to first add 1 and then divide with -2.

To correct this you have to change the mentioned lines to something like this:

    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;

Thanks,
Nick

@TheGreatRambler
Copy link
Copy Markdown
Author

Thank you for the fix, you're right!

@Th0rgal
Copy link
Copy Markdown

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