简体   繁体   中英

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. 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.

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). 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.

But which group to map to which port? 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. Therefore, we first need to map i,j to something which gives the same result for j,i but for no other inputs. One idea is 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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