Can you help me to find the best way to calculate hashcode for the class that has 3 int params (let say a
, b
, c
) and each param may have values in the predefined range? I mean that a
should be in some range from a1
to a2
, b
correspondingly from b1
to b2
and c
as you may guess from c1
to c2
. All these a1, a2, b1... are constant and known when the hashcode builds. I wish to avoid collisions.
Asked
Active
Viewed 81 times
0
-
1Well if the three ranges end up with more than 2^32 possible values, it's impossible to avoid collisions. What *are* the ranges? – Jon Skeet Jun 10 '18 at 13:31
-
assuming that the product of ranges does not exceed Integer.MAX_VALUE – Bizon4ik Jun 10 '18 at 14:26
1 Answers
1
First of all, make sure that total number of variants - product (a2 - a1) * (b2 - b1) * (c2 - c1)
fits into your hashcode capacity. If you are going to use 32-bit unsigned int, that value should be less than 2^32
.
Start constructing hashcode by picking some initial value s
(you can pick zero thus effectively omitting the initial value). Then for each param do the following:
- Multiply current hashcode value by current param range (i.e.
a2 - a1
) - Add current adjusted to range param value to the hashcode value
For your case of three params the formula is
((s*(a2 - a1) + (a - a1))*(b2 - b1) + (b - b1))*(c2 - c1) + (c - c1)
where s
is optional starting value
EDIT
Param value added should be adjusted to its range

Vasily Liaskovsky
- 2,248
- 1
- 17
- 32