Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create unique integer number from 3 different integers numbers(1 Oracle Long, 1 Date Field, 1 Short)

Tags:

numbers

hash

the thing is that, the 1st number is already ORACLE LONG, second one a Date (SQL DATE, no timestamp info extra), the last one being a Short value in the range 1000-100'000.
how can I create sort of hash value that will be unique for each combination optimally?

string concatenation and converting to long later:
I don't want this, for example.

Day Month

12 1 --> 121
1 12 --> 121

like image 882
yli Avatar asked Aug 31 '09 17:08

yli


2 Answers

When you have a few numeric values and need to have a single "unique" (that is, statistically improbable duplicate) value out of them you can usually use a formula like:

h = (a*P1 + b)*P2 + c

where P1 and P2 are either well-chosen numbers (e.g. if you know 'a' is always in the 1-31 range, you can use P1=32) or, when you know nothing particular about the allowable ranges of a,b,c best approach is to have P1 and P2 as big prime numbers (they have the least chance to generate values that collide). For an optimal solution the math is a bit more complex than that, but using prime numbers you can usually have a decent solution.

For example, Java implementation for .hashCode() for an array (or a String) is something like:

h = 0;
for (int i = 0; i < a.length; ++i)
    h = h * 31 + a[i];

Even though personally, I would have chosen a prime bigger than 31 as values inside a String can easily collide, since a delta of 31 places can be quite common, e.g.:

"BB".hashCode() == "Aa".hashCode() == 2122
like image 98
lapo Avatar answered Nov 11 '22 08:11

lapo


Your

12 1  --> 121
1 12  --> 121

problem is easily fixed by zero-padding your input numbers to the maximum width expected for each input field.

For example, if the first field can range from 0 to 10000 and the second field can range from 0 to 100, your example becomes:

00012 001 --> 00012001
00001 012 --> 00001012
like image 29
Chris Judge Avatar answered Nov 11 '22 06:11

Chris Judge