I have three numbers of type Long. Say, 1001, 2005, 8001. I need a method to generate a new number of type Long based on these three numbers. Any logic can be applied. Output should be always same whenever we use the same combination of numbers otherwise not. I need to solve this using Java.
CodePudding user response:
How about this?
long combine(long a, long b, long c) {
return Long.rotateLeft(a, 32) ^ Long.rotateLeft(b, 16) ^ c;
}
I used rotate rather than shift because you said "Concatenation is also not a option here. What if I use maximum values of Long?" Shift would shift some bits right out, but rotate will only move them around. The output will depend on all the bits of all three longs, but because they are rotated by different amounts, combine(a, b, c)
will produce a different result than combine(c, a, b)
(unless a == b
and b == c
, of course).
CodePudding user response:
Seems like a hash function may be what you need.
Hash functions map an input set to an output set, usually with the goal of it not being "easy" to know what the output will be from the input and such that small changes to the input yield different outputs. In your case the input is a tuple of three longs, and the output is a long.
It is deterministic, which fulfills your requirement for identical input yielding identical output.
From Wikipedia:
A hash procedure must be deterministic—meaning that for a given input value it must always generate the same hash value. In other words, it must be a function of the data to be hashed, in the mathematical sense of the term.
It is impossible to guarantee that the two different inputs will have the same outputs because of the Pigeonhole Principle, but a good hash function will be collision-resistant, meaning it is hard to find two inputs with the same output.
There are plenty of hash functions out there. For some examples:
For a more extensive list see this Wikipedia article:
The exact way to approach this is up to you, one implementation off the top of my head is to convert the longs to strings, concatenate them, and hash that concatted string, then return that hash as a long.