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

195 Views Asked by At

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?