Hash function in java

Asked

Viewed 656 times

-1

Could someone show me (and explain) a hash (scatter) function without being the? (key % size)? I would like it to be a simple one (and one that exists). In this case I have a table of 11 positions that should be based on the number of the Cpf your Dice, but without using Cpf % table size_table.

  • What is your exact doubt? May I suggest Integer.hashCode(), which is basically return this; as an easy hash example?

  • I have a table of 11 positions, I will receive a Cpf with 11 digits and using a scatter function I must place it in the table. But without using the Cpf function % size_table.

1 answer

0


You could interpret the 11 digits as one BigInteger, multiply by a very large prime number (ideally greater than a number of CPF, ie 12 digits), as for example 112287187009. So:

private static final BigInteger PRIME = new BigInteger("112287187009");
private static final BigInteger ONZE = BigInteger.valueOf(11);

public int hashCpf(String cpf) {
    BigInteger v = new BigInteger(cpf.replace(".", "").replace("-", ""));
    return BigInteger.multiply(PRIME).remainder(11).intValue();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.