ishika
ishika

Reputation: 3

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.

Upvotes: 0

Views: 102

Answers (1)

Peter
Peter

Reputation: 109

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

Upvotes: 0

Related Questions