# How to create the smallest possible unique number from one or many unordered numbers?

What I am looking for is very similiar to this question and that one, too.

I need to connect two SQL tables by a many-to-many relationship (artists and song names). To achieve what I'm trying to do I need to generate a unique number/id from one or multiple artist_ids.

The function should work something like

func(5, 2, 3) -> 18
func(2, 5, 3) -> 18
func(1, 7)    -> 9
func(1)       -> 4

meaning the order of arguments does not matter, only their values do. Furthermore the function should return the smallest possible unique value (in order to keep the SQL table somewhat clean).

Doing some research I came across Matt Di Pasquale's Blog describing an Unique Unordered Pairing Function based on the Cantor Pairing Function.

This piece of Java code actually works for two different numbers:

private static double unorderedPairing(int x, int y) {
if (x < y)
return Math.floor(x * (y - 1) + (y - x - 2)^2 / 4);
if (x > y)
return Math.floor(y * (x - 1) + (x - y - 2)^2 / 4);
return -1;
}
//unorderedPairing(5, 8) -> 36.0
//unorderedPairing(8, 5) -> 36.0
//unorderedPairing(2, 3) ->  3.0
//unorderedPairing(3, 2) ->  3.0

Nesting unorderedPairing(unorderedPairing(x, y), z) would not work as the argument order would start to matter.

Is there a function that does what I need it to do and takes a variable list of arguments?

• Do you have a bound on the number of arguments, and on the arguments themselves? – Exodd Sep 28 '15 at 20:09
• It seems that somebody tried to comment on the question using suggested edit. Maybe it might be even the OP, but they have two different accounts...? I will copy the comment below. – Martin Sleziak Sep 28 '15 at 20:31
• Copied from here: "ts very unlikely that there are more than 3 arguments, though, in one instance (one row out of ~163.000) there are 7 unique artist_ids to be passed to the func() that I am looking for. Theoretically the number of arguments can be the amount of artist_id's in the database. The highest artist_id value right now is around 50.000. Practically the number of arguments does not exceed 10." – Martin Sleziak Sep 28 '15 at 20:31
• Yes, sorry about that. I was not logged in when submitting the question. After I logged in the question somehow did no longer belong to me and I couldn't use the comments due to lack of reputation. However, now that I have verified my SE account it seems that the question has now been moved to my account. – phew Sep 28 '15 at 20:46