0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bizon4ik
  • 2,604
  • 4
  • 20
  • 46

1 Answers1

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:

  1. Multiply current hashcode value by current param range (i.e. a2 - a1)
  2. 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