2

I'm trying to generate n random numbers that depend on an input string. It would be a function generateNumbers(String input) that generates the same set of numbers for the same input string but entirely different numbers for a slightly different input string.

My question is: Is there an easy way to do this?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Pascal
  • 33
  • 4
  • 1
    [may be this can help you](http://stackoverflow.com/questions/10969733/create-a-uniform-random-number-based-on-a-hash) – jack jay Dec 30 '16 at 16:27
  • It doesn't sound like you want to actually generate random numbers, but a unique set of numbers based on a given input string. Or, put another way, a completely numerical hash. – nihilon Dec 30 '16 at 16:40

2 Answers2

0

I agree with nihlon, if what you want is a function f() returning an int such that f(string1) != f(string2) for any string1, string2 in some set of strings S, then you're looking for a perfect hash. Obviously, if S is the set of all possible strings, there are way more than 2^32, or even 2^64, so no such f() can exist returning an int or even long. Hence, the question is: how is S characterized?

Also, are you sure you need unique numbers for different strings? In most problem domains regular hashing is adequate...

Roberto Attias
  • 1,883
  • 1
  • 11
  • 21
0

As Roberto says, a hash is one way to do this, with a small possibility of two different strings hashing to the same value. That probability depends on the maximum size of string you allow and the bit-size of the resulting hash number.

You could also use an encryption, but then you would have to limit the string size to one or two blocks of a block cipher. Two blocks of AES is 32 characters, and will produce a 256 bit number.

Pick the smallest string size you can live with, and the largest hash size/block size you can work with. A non-cryptographic hash like the fnv hash will be faster than a cryptographic hash like SHA-256, but obviously less secure. You do not say how important security is to you.

rossum
  • 15,344
  • 1
  • 24
  • 38