这是一个自动回答的问题,源自这个更具体的问题OP 在选择错误的(恕我直言)答案后似乎失去了兴趣。
我确实检查了之前有关该主题的问题,但似乎没有一个能够解决该问题。
那有什么用呢?
假设您有 4 个人:Abdul、Beatrix、Charlie 和 Daria。
您想要存储有关这些人彼此之间的感受的信息
Abdul and Beatrix are in love
Beatrix and Charlie hate each other
Abdul and Charlie are good friends
Daria and Beatrix don't know each other
etc.
在简洁且缺乏诗意的计算机世界中,这可以翻译为:
relation (Abdul , Beatrix) = love;
relation (Beatrix, Charlie) = hate;
relation (Abdul , Charlie) = friendship;
etc.
换句话说,如果你想映射每一对人之间的关系,你将需要一个数据结构,允许你为每一对人维护唯一的值。
尽管有多种方法可以实现合适的数据结构,但在某些情况下,您可能希望该表是一个固定大小的数组,直接由表示给定关系的对进行索引。
一些定义:
given IN the set of the first N natural integers, let's call PN the sequence of all unordered pairs (a,b) of IN such that a <> b, sorted in lexicographic order.
用(希望)不那么神秘的英语,P 列举了 I 的两个元素之间所有可能的关系.
示例(对于 N = 4):
I4 = (0,1,2,3)
P4 = ((0,1),(0,2),(0,3),(1,2),(1,3),(2,3))
Note that the cardinality of PN is N(N-1)/2, so
the most compact zero-based index of PN will be in the [0..N(N-1)/2-1] range.
问题:
how can we index PN in a compact and efficient way?
换句话说,
- define a function pN(a,b) that, given a pair (a,b) of elements of IN, produces a unique index of PN in the range [0..N(N-1)/2-1]
- define the reverse-indexing function pN-1 that, given an index of PN, will produce the corresponding (a,b) pair
The way PN is arranged is of lesser importance, but a lexicographic order would probably be the most convenient.
example:
P4 = ((0,1),(0,2),(0,3),(1,2),(1,3),(2,3))
p4(1,3) = 4
p4-1(4) = (1,3)