6

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/

8
  • 3
    Um, you what? str.hashCode() % n should be exactly what you want. Commented Mar 28, 2017 at 0:17
  • 2
    I did that but for some strings its giving me value in negative instead of the range from 0 to n-1 Commented Mar 28, 2017 at 0:18
  • 2
    @ElliottFrisch Danger Will Robinson! Haven't you heard about polygenelubricants!? Math.abs(str.hashCode() % n) is what you want. Commented Mar 28, 2017 at 0:21
  • 1
    @Y0geshGupta What do you mean collision? You'll get collisions no matter what hash you use, because the number of strings greatly exceeds the size of an int Commented Mar 28, 2017 at 0:23
  • 1
    @Y0geshGupta there's a 1/4billion chance that any two strings will give the same hash. There's a 1/n chance that any two strings will give the same hash mod n Commented Mar 28, 2017 at 0:34

1 Answer 1

5

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.