Given an input string, I want to generate a "random" number between 0 and 1.

However given the same input string, the returned value should stay the same.

I tried something like:

Random gtiRandomGenerator = new Random(input.hashCode());
float gtiRandom = gtiRandomGenerator.nextFloat();

However FindBugs complained with Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)

5 Replies 5

Are you looking for this question?: Getting rid of FindBugs "Random object created and used only once" when Random is created in the constructor

Does your program intentionally create and use an instance of Random only once? Or is this instance being constantly re-created? If the latter then you'd want to keep a single instance of Random instead of re-creating it.

From there, you could probably achieve the intended functionality by storing previously-generated numbers in a hash set or something of that nature and checking that before generating a new number for any given input.

Seems like you could create one Random instance and setSeed with the hashcode as often as required.

Isn't the hashCode itself suffiecient for your needs? Actually, since you want a number from 0..1, Math.abs(((float) hashCode()) / Integer.MAX_VALUE)?

I think you've created a red herring for yourself by calling the output you want "random". One of your criteria is that the computation be deterministic -- always the same output for the same input -- so it's not random at all. You can nevertheless use a pseudorandom number generator to do the job by manipulating its seed, but that seems a bit overkill.

Hash Function will be your friend.

Your Reply

By clicking “Post Your Reply”, 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.