Reputation: 330
I have a implementation of the Cantor Pairing Function in Java which I wrote 2 years ago. Now then I'm moving more to iOS I need the same thing in Objective-C.
The problem is, at least from my point of view, in Java I had to implement a BigSqrt Class which I did by my self. Because theoreticaly I can now Pair any size of number.
Because I am new to iOS I really do not know if I have to implement all the things again for objective-C or is there something already implemented. If so, could someone give me a hint where to start implementing the Cantor Pairing function for any size of "Integer" in Objective-C ?
thanks
Upvotes: 2
Views: 2272
Reputation: 6353
I used this to set tags on tableview cells:
NSUInteger cantorPair(NSIndexPath *indexPath)
{
NSUInteger x = indexPath.section;
NSUInteger y = indexPath.row;
return ((x + y) * (x + y + 1)) / 2 + y;
}
NSIndexPath *reverseCantorPair(NSUInteger z)
{
NSUInteger t = floor((-1.0f + sqrt(1.0f + 8.0f * z))/2.0f);
NSUInteger x = t * (t + 3) / 2 - z;
NSUInteger y = z - t * (t + 1) / 2;
return [NSIndexPath indexPathForRow:y inSection:x];
}
Upvotes: 6
Reputation: 169
This is for a C# version, but should be almost identical in Objective-C:
http://sachiniscool.blogspot.com/2011/06/cantor-pairing-function-and-reversal.html
int CantorPair(short x, short y)
{
return ((x + y) * (x + y + 1)) / 2 + y;
}
and to reverse the pairing
short[] Reverse(int z)
{
short[] pair = new short[2];
int t = (int)Math.Floor((-1D + Math.Sqrt(1D + 8 * z))/2D);
int x = t * (t + 3) / 2 - z;
int y = z - t * (t + 1) / 2;
pair[0] = (short)x;
pair[1] = (short)y;
return pair;
}
Upvotes: 2