Last active
August 7, 2024 14:57
-
-
Save TheGreatRambler/048f4b38ca561e6566e0e0f6e71b7739 to your computer and use it in GitHub Desktop.
A pairing function (szudzik) that supports negative numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]; | |
}; |
Thank you for the fix, you're right!
Thanks nick and TheGreatRambler!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
. In the else-branches of your
getindex
function you multiply x respectively y with-2
and then subtract1
from the result. Therefore to invert this part of the function you need to first add1
and then divide with-2
.To correct this you have to change the mentioned lines to something like this:
Thanks,
Nick