简体   繁体   English

如何在 python 上生成唯一的数字对

[英]How to generate unique pairs of numbers on python

So I'm working on a chat application right now.. let's say we have User1, User2, User3, ...UserN.所以我现在正在开发一个聊天应用程序。假设我们有 User1、User2、User3、...UserN。 I want to generate a unique port number for each pair.我想为每对生成一个唯一的端口号。 Like User1 and User2 will have 5000, User1 and User3 will have 5070, User2 and User3 will have 5500, etc etc.. basically every User should have a different port number for other users.. but both of the Users should have the same one for each of them.就像 User1 和 User2 将有 5000,User1 和 User3 将有 5070,User2 和 User3 将有 5500 等等。基本上每个用户应该有不同的端口号给其他用户.. 但两个用户应该有相同的对于他们每个人。

So if I understand correctly, you're looking for a way to map every pair i,j from User-i and User-j to a number between 0 and 65535 (or whichever your range is).因此,如果我理解正确,您正在寻找一种方法来 map 从User-iUser-j的每对i,j065535之间的数字(或您的范围)。 By the way, this means that you're going to have a maximum of 65535 pairs of users, and since there are N * (N-1) / 2 pairs, that means about 362 users.顺便说一句,这意味着您将拥有最多65535对用户,并且由于有N * (N-1) / 2对,这意味着大约362个用户。

But which group to map to which port?但是哪个组到 map 到哪个端口? Let's say User-0 gets ports 1 to N , next user N+1 to 2N , etc This way you can map i,j to f(i,j) = N*i + j , which is a 1-1 function, however i,j gives a different result than j,i , which is not what you want.假设User-0获得端口1N ,下一个用户N+12N等这样你可以 map i,jf(i,j) = N*i + j ,这是一个 1-1 function,但是i,j给出的结果与j,i不同,这不是您想要的。 Therefore, we first need to map i,j to something which gives the same result for j,i but for no other inputs.因此,我们首先需要将 map i,j得到对j,i给出相同结果但没有其他输入的东西。 One idea is g(i,j) = (i,j) if i<j else (j,i) .一个想法是g(i,j) = (i,j) if i<j else (j,i) In other words, sort the numbers first.换句话说,首先对数字进行排序。

Now User1, User2 are mapped to 1,2 -> 1,2 -> 360*1 + 2 = 362 And also User2, User1 are mapped to 2,1 -> 1,2 -> 360*1 + 2 = 362现在User1, User2映射到1,2 -> 1,2 -> 360*1 + 2 = 362而且User2, User1映射到2,1 -> 1,2 -> 360*1 + 2 = 362

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM