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]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks nick and TheGreatRambler!