映射两个整数之一,以独特的和确定的方式整数、独特、两个、方式

2023-09-10 22:24:59 作者:偷看先生一眼.

想象一下,两个正整数A和B.我想这两个合并成一个单一的整数C.

Imagine two positive integers A and B. I want to combine these two into a single integer C.

不能有任何其他的整数D和E相结合为C. 因此,结合它们与加法运算符不能正常工作。如30 + 10 = 40 = 40 + 0 = 39 + 1 无论是做concatination工作。例如31+2= 312 =3+12

There can be no other integers D and E which combine to C. So combining them with the addition operator doesn't work. Eg 30 + 10 = 40 = 40 + 0 = 39 + 1 Neither does concatination work. Eg "31" + "2" = 312 = "3" + "12"

此组合操作也应是确定的(总是产生相同的结果具有相同的输入)的和的应该总是产生一个整数上正或整数的负侧。

This combination operation should also be deterministic (always yield the same result with the same inputs) and should always yield an integer on either the positive or the negative side of integers.

推荐答案

您正在寻找一个双射 N×N个 - > ñ映射。这些被用于例如的衔接的。有一个在所谓此PDF 一个介绍的的配对功能。维基百科介绍具体的配对功能,即康托尔配对功能:

You're looking for a bijective NxN -> N mapping. These are used for e.g. dovetailing. Have a look at this PDF for an introduction to so-called pairing functions. Wikipedia introduces a specific pairing function, namely the Cantor pairing function:

的圆周率(K1,K2)= 1/2(K 1 + K)(K 1 + K + 1)+ K2 的

三备注:

正如其他人明确表示,如果计划实现配对功能,你很快就会发现,你需要任意大的整数(大数)。 如果您不想让对区分(A,B)和(B,A),然后排序并应用配对功能前湾 其实我撒了谎。您正在寻找一个双射 ZXZ - &GT; ñ映射。康托尔的功能只适用于非负数。这不是一个问题,但是,因为它很容易定义一个双射 F:Z - &GT; ñ,如下所示: F(N)= N * 2 的如果n> = 0 F(N)= N * 2 - 1 的如果n&LT; 0 As others have made clear, if you plan to implement a pairing function, you may soon find you need arbitrarily large integers (bignums). If you don't want to make a distinction between the pairs (a, b) and (b, a), then sort a and b before applying the pairing function. Actually I lied. You are looking for a bijective ZxZ -> N mapping. Cantor's function only works on non-negative numbers. This is not a problem however, because it's easy to define a bijection f : Z -> N, like so: f(n) = n * 2 if n >= 0 f(n) = -n * 2 - 1 if n < 0