Y0gesh Gupta
Y0gesh Gupta

Reputation: 2204

How to hash a string to integer with a range in Java

Suppose I have n number of strings, now I want to map each string to an integer within range from 0 to n-1 using a function such that whenever I call a function and pass the string and the n it will give me same and unique mapping on the go. So suppose if I have 4 strings "str1","str2","str3","str4" then the mapping will be from 0-3 and unique.

I tried doing something like : str.hashCode() % n, this is giving me the same mapping but is not within the range of 0 to n-1. I found something in PHP which is similar to this here-

https://madcoda.com/2014/04/how-to-hash-a-string-to-integer-with-a-range-php/

Upvotes: 6

Views: 9641

Answers (1)

Fattie
Fattie

Reputation: 12268

For the record

In Java, hash random strings down to an integer:

Math.abs(str.hashCode() % 7)

Result will be 0 inclusive to 6 inclusive.

Note:

If the input strings are really random and the same length etc (for example ... the input is a whole lot of uuids) then the output here will be randomly balanced.

If the input is - say - many human names, it is very unlikely the output will be randomly balanced.

Note:

What the OP was asking literally in the headline is answered here.

In fact, what the OP was asking about (in the body) has no connection at all to hashing. (That would just be a lookup table, a regex or such.)

Upvotes: 5

Related Questions